View rendering in iOS 4.2 - iphone

I built a custom view to make chat messages according to this tutorial
It is working fine if the app is directly compiled on device.But while creating an ipa file and installing it via iTunes, in iOS 4.2, the height of the chat bubbles are stretched more than the required size and causes overlapping of chat bubbles. But it is working fine in iOS 5.What would be the reason for this?Thanks in advance.
EDIT:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = (NSDictionary *)[messages objectAtIndex:indexPath.row];
NSString *msg = [[dict objectForKey:#"message"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [msg sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.height += padding*3;
CGFloat height = size.height < 65 ? 65 : size.height;
return height;
}
EDIT 2:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MessageCellIdentifier";
SMMessageViewTableCell *cell = (SMMessageViewTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[SMMessageViewTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if ([messages count]>0) {
NSLog(#"index path is %d",indexPath.row);
NSDictionary *s = (NSDictionary *) [messages objectAtIndex:indexPath.row];
NSString *sender =allTrim([s objectForKey:#"sender"]);
NSString *senderId = [s objectForKey:#"friendId"];
NSString *message = [s objectForKey:#"message"];
if ([message length]<8)
{
message=[message stringByAppendingString:#" "];
}
message=[message stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *time = [s objectForKey:#"time"];
NSString *locatn = [s objectForKey:#"friendLocation"];
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [message sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.width += (padding/2);
cell.messageContentView.text = [message stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.userInteractionEnabled = YES;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
UIImage *bgImage = nil;
if ([senderId isEqualToString:UIAppDelegate.userId]) {
sender=#"Me";
bgImage = [[UIImage imageNamed:#"ChatBubbleGray.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.messageContentView setFrame:CGRectMake(padding, padding*2, size.width, size.height)];
[cell.bgImageView setFrame:CGRectMake( cell.messageContentView.frame.origin.x - padding/2,
cell.messageContentView.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.senderAndTimeLabel.textAlignment=UITextAlignmentLeft;
} else {
bgImage = [[UIImage imageNamed:#"ChatBubbleGreen.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.messageContentView setFrame:CGRectMake(320 - size.width - padding,
padding*2,
size.width,
size.height)];
[cell.bgImageView setFrame:CGRectMake(cell.messageContentView.frame.origin.x - padding/2,
cell.messageContentView.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.senderAndTimeLabel.textAlignment=UITextAlignmentRight;
}
cell.bgImageView.image = bgImage;
if ([locatn length]>0)
{
cell.senderAndTimeLabel.text = [NSString stringWithFormat:#"%#, %# %#", sender, locatn, time];
}
cell.senderAndTimeLabel.text = [NSString stringWithFormat:#"%#, %#", sender, time];
}
return cell;
}

Have you tried direct building in release? Typically direct compilation is done with out optimizations applied. I've never heard of this happening but, it's possible some optimization is wacking out your views.

I built [...] according to a tutorial
There's your first programming error. ;)
Kidding aside, running a non-debug executable causes the app to have an uninitialized, non-zeroed heap where the instance variable values are held. If you don't initialize all your instance variables, it may lead to unpredictable behavior. That may be an issue here, but we can't see all the code involved, so we can only bet on what may be wrong. And the code you did attach, doesn't seem to be the problem. It's the drawing of bubbles that's broken.

Related

bubble-message with avatar images and avatar name with time-stamps

I have to implement bubble messages with the senders AVATAR and Sender's name with time-stamps same as below screen shot.
I have successfully implemented the simple bubble type messaging. Right now I have some good Git-hub projects which provide me but what I need is something different.
I had even used acanichat but no luck.
so can anyone suggest me good tutorial for the same? or anyone have already done this with this Git-hub Library or with any other library?
I want a bubble-message with the senders AVATAR and Sender's name with time-stamps, please take a look at following image.
Your suggestion are appreciable.
Why not you create your own chat Table ? You just need to create Two custom Cells and With the help of XIB file you can give any Look you want.
Use Differentiators and conditions like Below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
CGSize boundingSize = CGSizeMake(messageWidth-20, 10000000);
CGSize itemTextSize = [messageText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
float textHeight = itemTextSize.height+7;
if (messageType isEqualToString:#"textByme"]) {
CustomCell1 *cell = (CustomCell1 *)[self.tableview dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell1" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
UIImageView *bubbleImage=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"chatbubble"] stretchableImageWithLeftCapWidth:15 topCapHeight:15]];
bubbleImage.tag=55;
[cell.contentView addSubview:bubbleImage];
[bubbleImage setFrame:CGRectMake(255-itemTextSize.width,5,itemTextSize.width+10,textHeight)];
UITextView *messageTextview=[[UITextView alloc]initWithFrame:CGRectMake(250-itemTextSize.width,0,itemTextSize.width+15, textHeight)];
[cell.contentView addSubview:messageTextview];
messageTextview.editable=NO;
messageTextview.text = messageText;
messageTextview.dataDetectorTypes=UIDataDetectorTypeAll;
messageTextview.textAlignment=NSTextAlignmentJustified;
messageTextview.font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
messageTextview.backgroundColor=[UIColor clearColor];
messageTextview.tag=indexPath.row;
cell.Avatar_Image.image=[UIImage imageNamed:#"avatar.png"];
cell.time_Label.text=data.messageTime;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
messageTextview.scrollEnabled=NO;
return cell;
}
else{
CustomCell2 *cell = (CustomCell2 *)[self.tableview dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell2" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
UIImageView *bubbleImage=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"chatbubble"] stretchableImageWithLeftCapWidth:15 topCapHeight:15]];
[cell.contentView addSubview:bubbleImage];
[bubbleImage setFrame:CGRectMake(50,5, itemTextSize.width+10, textHeight)];
bubbleImage.tag=56;
UITextView *messageTextview=[[UITextView alloc]initWithFrame:CGRectMake(50,0,itemTextSize.width+15, textHeight)];
[cell.contentView addSubview:messageTextview];
messageTextview.editable=NO;
messageTextview.text = messageText;
messageTextview.dataDetectorTypes=UIDataDetectorTypeAll;
messageTextview.textAlignment=NSTextAlignmentJustified;
messageTextview.backgroundColor=[UIColor clearColor];
messageTextview.font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
messageTextview.scrollEnabled=NO;
messageTextview.tag=indexPath.row;
cell.Avatar_Image.image=[UIImage imageNamed:#"avatar"];
cell.time_Label.text=feed_data.messageTime;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}
}
For Height:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float cellHeight;
// text
NSString *messageText = #"Your text";
//
CGSize boundingSize = CGSizeMake(messageWidth-20, 10000000);
CGSize itemTextSize = [messageText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
// plain text
cellHeight = itemTextSize.height;
if (cellHeight<25) {
cellHeight=25;
}
return cellHeight+30;
}

Modify multiple rows on uitableview on view load

I have a UITableView that should have 33 rows. Each row represents a specific time slot in a day. When the view that holds the table view loads, I need it to populate each row accordingly.
I have an array of reservation objects that gets passed to the view. Each reservation contains a slot number, a reservation name and the duration of the reservation in slots.
What is the best way to populate the table, I am currently iterating through the array of reservations in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method.
This is not giving me the results or the behavior I am expecting. The performance is extremly poor as it keeps iterating through loops and cells that shouldn't be blue are blue after scrolling. What is the best way to approach this? I have included the code below.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 33;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *timeStamp = [NSString stringWithFormat:#"%.2f", (indexPath.row + 14.0 ) / 2.0];
timeStamp = [timeStamp stringByReplacingOccurrencesOfString:#".50" withString:#":30"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:#"%#: ", timeStamp];
for (Reservation *temp in bookingsArray) {
if ((temp.slotNumber - 1) == indexPath.row) {
cell.textLabel.text = [NSString stringWithFormat:#"%#: %#", timeStamp, temp.reservationName];
cell.contentView.backgroundColor = [UIColor blueColor];
}
for (NSNumber *tempNo in temp.slotIdentifiers) {
if ([tempNo intValue] -1 == indexPath.row) {
//cell.textLabel.text = [NSString stringWithFormat:#"%#: Booked", timeStamp];
cell.contentView.backgroundColor = [UIColor blueColor];
}
}
}
return cell;
}
UPDATE
Trying the following gives me strange behaviour where all the cells turn blue after I start scrolling.
- (void)viewDidLoad
{
[super viewDidLoad];
bookManager = appDelegate.bookingManager;
bookingsArray = [[NSArray alloc] initWithArray:[bookManager getBookingsForCourt:1 onDate:[NSDate date]]];
namesArray = [[NSMutableDictionary alloc] init];
slotIndexSet = [NSMutableIndexSet indexSet];
for (int c = 0; c < 33; c++) {
[namesArray setObject:#"Available" forKey:[NSNumber numberWithInt:c]];
}
for (Reservation *temp in bookingsArray) {
[namesArray setObject:temp.reservationName forKey:[NSNumber numberWithInt:temp.slotNumber]];
for (NSNumber *slotNo in temp.slotIdentifiers) {
[slotIndexSet addIndex:[slotNo intValue] + 1];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *timeStamp = [NSString stringWithFormat:#"%.2f", (indexPath.row + 14.0 ) / 2.0];
timeStamp = [timeStamp stringByReplacingOccurrencesOfString:#".50" withString:#":30"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:#"%#: ", timeStamp];
cell.textLabel.text = [namesArray objectForKey:[NSNumber numberWithInt:indexPath.row]];
if ([slotIndexSet containsIndex:indexPath.row]) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
return cell;
}
You need to do two things to speed this up:
Convert bookingsArray to a bookingBySlotNumber array in such a way that the object at index i has slotNumber - 1 equal to i. You can do it by iterating over the original bookings array when you receive it.
Create a NSIndexSet called isBookedBySlotNumber containing indexes of items that have been booked. You can prepare it by going through all Reservation.slotIdentifiers, and marking the indexes of isBookedBySlotNumber for items that have been booked.
With these two pre-processed items in place, you can eliminate the nested loops altogether: the outer one will be replaced by a lookup in bookingBySlotNumber, and the inner one - by a loopup in isBookedBySlotNumber.

UITableView only shows data from JSON when I scroll up and down

UITableView only shows data from JSON array when I scroll up and down. When I load the table view it shows cells but they are blank and as I scroll up and down it then starts showing the data.
How do I show the cells with data without scrolling?
- (void)requestFinished:(ASIHTTPRequest *)request
{
if (request.responseStatusCode == 400) {
NSLog( #"Code already used");
} else if (request.responseStatusCode == 403) {
NSLog( #"Code already used");
} else if (request.responseStatusCode == 200) {
NSLog(#"%#",[request responseString]);
NSString *response = [request responseString];
const char *convert = [response UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
responseArray = [responseString JSONValue];
Nrows = [responseArray count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dict = [responseArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [dict objectForKey:#"allfeeds"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.textLabel.minimumFontSize = 10;
cell.textLabel.numberOfLines = 4;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.text = [dict objectForKey:#"allfeeds2"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
When you finish your request and you set the array, make sure to call [self.tableView reloadData];
For performance and animation purposes, table views don't reload their data when the source changes.
Instead of starting the request asynchronously (non-blocking)
[request startAsynchronously];
Try doing it synchronously (blocking)
[request startSynchronously];
I had a similar issue and got my answer at the Apple's Developer Forums a while ago, this solved my problem:
From what you've described, I'd guess the problem is more likely to be in cellForRowAtIndexPath or wherever you do the actual configuration of a cell than in the code you've posted. A problem like yours can happen when dequeueReusableCellWithIdentifier gives you back an existing cell, but you don't reset its existing state completely.
The full question and answers can be found here (requires login): https://devforums.apple.com/message/502483#502483
These problems are usually caused by the UITableView cache, that dequeues his available cached UITableViewCell with the same CellIdentifier (in your case - #"Cell").
Try creating a cell identifier for each and everyone of your table's cells. You can create this variance using the NSIndexPath param in the following way :
NSString* cellIdentifier = [NSString stringWithFormat:#"Cell%d",indexPath.row];
That of course, under the assumption you're not changing the content of your cells after you load the data.

Array out of bounds and slow slow app

So below is my code for my controller, which I have four of one for each tab on the tab bar. I have two issues.
I am getting an array out bounds but I can't chase it down. Am I missing something here?
Second when my app starts up it take 5 - 8 seconds before it loads the first view of the tab bar. Once it loads and I click another tab, the tab doesn't turn blue and the app sits there for 3 seconds then finally switches. I am a noob and am struggling here. I think this issue might be fixed by fetching the data in another thread or something? I am sure this controller is full of bugs.
import "AllMackTableViewController.h"
import "PostDetailViewController.h"
import "MackdabMobileAppDelegate.h"
import <QuartzCore/QuartzCore.h>
import "Post.h"
define FONT_SIZE 14.0f
define CELL_CONTENT_WIDTH 254.0f
define CELL_CONTENT_MARGIN 5.0f
#implementation AllMackTableViewController
#synthesize jsonArray;
#synthesize localJsonArray;
#synthesize postDetailViewController;
#synthesize allPostsTableView;
#synthesize fetchedResultsController, managedObjectContext;
#synthesize minuteTimer;
#synthesize regionsTimer;
pragma mark
pragma mark View lifecycle
(void)viewDidLoad {
[super viewDidLoad];
self.title = NSLocalizedString(#"Feed", #"You're Matching Posts");
UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
self.navigationItem.rightBarButtonItem = refreshButton;
allPostsTableView.delegate = self;
[refreshButton release];
[self refresh];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
(void)scrollViewDidScroll:(UIScrollView *) scrollView;
{
CGFloat scrollHeight = scrollView.contentSize.height;
CGPoint p = scrollView.contentOffset;
//NSLog(#"x = %f, y = %f", p.x, p.y);
}
(void)viewWillAppear:(BOOL)animated {
/*
Set up two timers, one that fires every minute, the other every fifteen minutes.
1/ The time displayed for each time zone must be updated every minute on the minute.
2/ Time zone data is cached. Some time zones are based on 15 minute differences from GMT, so update the cache every 15 minutes, on the "quarter".
*/
NSTimer *timer;
NSDate *date = [NSDate date];
/*
Set up a timer to update the table view every minute on the minute so that it shows the current time.
*/
NSDate *oneMinuteFromNow = [date dateByAddingTimeInterval:60];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *timerDateComponents = [calendar components:unitFlags fromDate:oneMinuteFromNow];
// Add 1 second to make sure the minute update has passed when the timer fires.
[timerDateComponents setSecond:1];
NSDate *minuteTimerDate = [calendar dateFromComponents:timerDateComponents];
timer = [[NSTimer alloc] initWithFireDate:minuteTimerDate interval:60 target:self selector:#selector(updateTime:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
self.minuteTimer = timer;
[timer release];
}
pragma mark
pragma mark Table view data source
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
// return [self.localJsonArray count];
NSLog(#"Setting numberOfRowsInSection to %i",[self.localJsonArray count]);
if ( [jsonArray count] < 9 ) {
return [self.localJsonArray count];
NSLog(#"Setting numberOfRowsInSection to %i inside of non add one.",[self.localJsonArray count]);
} else {
return [self.localJsonArray count] + 1;
}
}
(void)updateTime:(NSTimer *)timer {
/*
To display the current time, redisplay the time labels.
Don't reload the table view's data as this is unnecessarily expensive it recalculates the number of cells and the height of each item to determine the total height of the view etc. The external dimensions of the cells haven't changed, just their contents.
*/
NSArray *visibleCells = self.tableView.visibleCells;
for (PostTableCustomCellController *cell in visibleCells) {
[cell redisplay];
}
[self updateRegions];
}
(NSString *)dateDiff:(NSString *)origDate {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:#"EEE, dd MMM yy HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * 1;
if(ti < 1) {
return #"never";
} else if (ti < 60) {
return #"less than a minute ago";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:#"%d minutes ago", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:#"%d hours ago", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d days ago", diff];
} else {
return #"never";
}
}
(void)updateRegions {
/*
The following sets the date for the regions, hence also for the time zone wrappers. This has the sideeffect of "faulting" the time zone wrappers (see TimeZoneWrapper's setDate: method), so can be used to relieve memory pressure.
*/
NSDate *date = [NSDate date];
for (Post *post in localJsonArray) {
post.timeRemaining = [self dateDiff:post.deadline];
}
}
// Customize the appearance of table view cells.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *distance;
UIImage *image = [UIImage imageNamed:#"imageA.png"];
static NSString *CellIdentifier = #"customCell"; // This is identifier given in IB jason set this.
PostTableCustomCellController *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (indexPath.row != [localJsonArray count] ) {
if (cell == nil) {
NSLog(#"Cell created");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"PostTableCustomCellController" owner:nil options:nil];
for(id currentObject in nibObjects)
{
if([currentObject isKindOfClass:[PostTableCustomCellController class]])
{
cell = (PostTableCustomCellController *)currentObject;
}
}
}
Post *post = [localJsonArray objectAtIndex:indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"];
//Optionally for time zone converstions
//[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:post.deadline];
cell.authorName.text = post.author;
cell.deadline.text = stringFromDate;
cell.budget.text = post.budget;
cell.description.text = post.description;
[[cell avatar] setImage:[UIImage imageNamed:#"butterfly.jpeg"]];
[stringFromDate release];
NSLog([NSString stringWithFormat:#"%#", post.distance]);
if([#"" isEqualToString: post.distance] || nil == post.distance) {
cell.distance.text = #"1 mi.";
}else{
cell.distance.text = #"25 mi.";
}
Post *myPost = [localJsonArray objectAtIndex:[indexPath row]];
// Might can remove these
UILabel *locationLabel = (UILabel *) [cell distance];
UITextView *postTextView = (UITextView *) [cell description];
//CGSize maximumLabelSize = CGSizeMake(254,88.0f);
NSString *text;
CGSize constraint;
CGSize size;
CGFloat height;
CGFloat realHeight;
CGSize expectedLabelSize;
text = myPost.description;
constraint = CGSizeMake(CELL_CONTENT_WIDTH (CELL_CONTENT_MARGIN * 2), 88.0f);
size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
height = MAX(size.height, 35.0f);
realHeight = height + 36.0f (10);
expectedLabelSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(252.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = postTextView.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = 252;
postTextView.frame = newFrame;
[[cell description] sizeToFit];
[[cell viewForBackground] sizeToFit];
[cell setNeedsDisplay];
}// Ok, all done for filling the normal cells, next we probaply reach the +1 index, which doesn’t contain anything yet
if ( [jsonArray count] == 9 ) { // Only call this if the array count is 25
if(indexPath.row == [localJsonArray count] ) { // Here we check if we reached the end of the index, so the +1 row
if (cell == nil) {
cell = [[[PostTableCustomCellController alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Reset previous content of the cell, I have these defined in a UITableCell subclass, change them where needed
cell.authorName.text = nil;
cell.deadline.text = nil;
cell.budget.text = nil;
cell.description.text = nil;
// Here we create the ‘Load more’ cell
UILabel *loadMore =[[UILabel alloc]initWithFrame: CGRectMake(20,0,362,100)];
loadMore.textColor = [UIColor blackColor];
loadMore.highlightedTextColor = [UIColor darkGrayColor];
loadMore.backgroundColor = [UIColor clearColor];
loadMore.font=[UIFont fontWithName:#"Verdana" size:20];
loadMore.textAlignment=UITextAlignmentCenter;
loadMore.font=[UIFont boldSystemFontOfSize:20];
loadMore.text=#"Load More..";
[cell addSubview:loadMore];
}
}
return cell;
}
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row != [localJsonArray count] ) {
Post *myPost = [localJsonArray objectAtIndex:[indexPath row]];
NSString *text = myPost.description;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH (CELL_CONTENT_MARGIN * 2), 88.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 35.0f);
return height + (CELL_CONTENT_MARGIN * 2) + 28.0f;
}else{
return 100.0f;
}
}
(IBAction)nextTwentyFivePlease:(NSString *)thePostID{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.jsonArray = [Post findNextTwentyFiveRemote:thePostID];
if (self.localJsonArray == nil) {
self.localJsonArray = [[NSMutableArray alloc]init]; // init the local array if it’s empty
}
[self.localJsonArray addObjectsFromArray:self.jsonArray];
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
(IBAction)refresh {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.jsonArray = [Post findAllRemote];
if (self.localJsonArray == nil) {
self.localJsonArray = [[NSMutableArray alloc]init]; // init the local array if it’s empty
}
[self.localJsonArray addObjectsFromArray:self.jsonArray];
//self.localJsonArray = [Post findAllRemote];
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
pragma mark
pragma mark Table view delegate
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ( [jsonArray count] == 9 ) { // only check for the load more function if we have 25 results in the dynamic array
if (indexPath.row == [localJsonArray count] ) { // See if we reached the +1 in the results
Post *tempPost = [jsonArray objectAtIndex:indexPath.row];
NSLog('What is at tempPost');
[self nextTwentyFivePlease:tempPost.postID]; // function to load more results
}
} else {
NSInteger row = [indexPath row];
if (self.postDetailViewController == nil) {
PostDetailViewController *aPostDetail = [[PostDetailViewController alloc] initWithNibName:#"PostDetailView" bundle:nil];
self.postDetailViewController = aPostDetail;
postDetailViewController.post = [localJsonArray objectAtIndex:row];
[aPostDetail release];
}
postDetailViewController.title = [NSString stringWithFormat:#"Details"];
MackdabMobileAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.allMacksNavController pushViewController:postDetailViewController animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
pragma mark
pragma mark Timer set accessor methods
(void)setMinuteTimer:(NSTimer *)newTimer {
if (minuteTimer != newTimer) {
[minuteTimer invalidate];
minuteTimer = newTimer;
}
}
(void)setRegionsTimer:(NSTimer *)newTimer {
if (regionsTimer != newTimer) {
[regionsTimer invalidate];
regionsTimer = newTimer;
}
}
pragma mark
pragma mark Memory management
(void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
(void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
(void)dealloc {
[allPostsTableView release];
[postDetailViewController release];
[localJsonArray release]; // may need to remove this
[super dealloc];
}
#end
In your refresh method which is called in viewDidLoad, it appears that it is doing a bunch of network access to download some information. That would explain why it is taking so long to show your initial tab.
You'll want to do that network access in a background thread so that your UI doesn't block. Then once you've gotten the results back you can update your UI from the main thread. Something like:
- (IBAction) refresh {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self performSelectorInBackground:#selector(refreshInBackground) withObject:nil];
}
- (void) refreshInBackground {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
self.jsonArray = [Post findAllRemote];
if (self.localJsonArray == nil) {
self.localJsonArray = [[NSMutableArray alloc]init]; // init the local array if it’s empty
}
[self.localJsonArray addObjectsFromArray:self.jsonArray];
[self performSelectorOnMainThread:#selector(refreshComplete) withObject:nil waitUntilDone:NO];
}
- (void) refreshComplete {
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
EDIT: As Rob noted in the comment below, you'll want to add some kind of flag (or semaphore) to avoid firing off multiple -refresh calls at the same time. Threading and race conditions are always a tricky bit, but my goal above was just to get you moving in the right direction so that you can use background threads for your network calls.

Reading plist into TableView

I started this project with a simple plist of a dictionary with two arrays of strings. I now want to add more information and want to use this plist structure:
Root - Dictionary - (2 items)
Standard - Array - (3 items)
Item 0 - Dictionary - (4 items)
Color - String - Red
Rvalue - String - 255
Gvalue - String - 0
Bvalue - String - 0
Sorry about typing in the plist but the site would not let me post an image
I know that the RGB values could be numbers instead of strings but I have a reason for them being strings.
This is the code I used to read the simple plist:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *colorSection = [colors objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: SectionsTableIdentifier] autorelease];
}
cell.textLabel.text = [colorSection objectAtIndex:row];
[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; //add disclosure button to rows
return cell;
}
My question is what is the specific code to retrieve the contents of the color dictionaries to get the Colors for the cell.textLabel.text and also read the RGB values to add a subtitle. I've been working on this for several days and have read references and lots of examples and unfortunately can't solve the problem. Your assistance will be greatly appreciated.
So providing you have your Standard - Array stored against a Array you've defined in your .h file then something like this would work. In this example the array is stored against self.coloursArray.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: SectionsTableIdentifier] autorelease];
}
NSString* ColourString = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Colour"];
NSString* rValue = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Rvalue"];
NSString* gValue = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Gvalue"];
NSString* bValue = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Bvalue"];
cell.textLabel.text = ColourString;
NSString* subCellString = [NSString stringWithFormat:#"%#:%#:%#", rValue, gValue, bValue];
}
Hopefully that'll give a a hand.
First, do not use -[UITableViewCell initWithFrame:reuseIdentifier:]. It has been deprecated and will give you a warning, plus it will make your subtitle harder to implement. This code is a modified version of yours which loads the information, sets the title to the Color property, and sets the subtitle to a string containing the Rvalue, Gvalue, and Bvalue properties.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *colorSection = [colors objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil) {
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: SectionsTableIdentifier] autorelease];
}
NSDictionary *color = [colorSection objectAtIndex:row];
cell.textLabel.text = [color objectForKey:#"Color"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#, %#, %#",[color objectForKey:#"Rvalue"],[color objectForKey:#"Gvalue"],[color objectForKey:#"Bvalue"]];
[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; //add disclosure button to rows
return cell;
}