How to prevent counting an empty NSMutableArray
I would like to simulate the SMS Bubbles of the iPhone for my own app. I found some nice code overhere (FYI): http://vimeo.com/8718829 . It is a restyled UITableView. Exactly what a wanted.
Here is开发者_StackOverflow the problem: - The Tableview is filled with an array of messages - It needs to be a NSMutable array because you want to add messages on the fly. - When there are no messages yet, the message-array is empty. - But counting an empty NSMutableArray causes an exeception, the app crashes. (you need the count for scrolling).
So what is a nice solution for that? I now pre fill the array with "". But that is very ugly. You see a mini bubble on the screen.
Can you hide cells? In the example on the video, there are already 2 messages so the problem does no occur.
Any suggestion is welcome. Tnx Christian
Actually counting an empty array does not raise any exception. I think the problem is here:
- (void)add {
if(![field.text isEqualToString:@""])
{
[messages addObject:field.text];
[tbl reloadData];
NSUInteger index = [messages count] - 1;
[tbl scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
field.text = @"";
}
}
As the "-1" index cannot exist. You can edit that line to
NSUInteger index = MAX(0, [messages count] - 1);
And it should work.
You can count an empty array (I assume you mean [arrayName count]) as long as its alloc'd so make sure its initialized somewhere earlier.
精彩评论