Add row to UITableView crash if initially empty table
I'm using the code below to refresh a tableview which I just added a row into. The code works for adding a row to the table if there is at least 1 row already in the table. However, it crashes if it was initially an empty table.
NSArray *indexPaths = [NSArray arrayWithObjects: [NSIndexPath indexPathForRow:[commentsArray count] inSection:0], nil];
[commentsTableView beginUpdates];
[commentsArray addObject:newestEntry];
[commentsTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
[commentsTableView endUpdates];
[commentsTableView scrollToBottom:YES];
The crash response I get is:
*** Terminat开发者_如何学编程ing app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).'
Can someone help me?
Well, the error is telling you the when UIKit calls tableView:numberOfRowsInSection
is returning 0
both before and after your updates. So either you have an error in that method or in your update. You said in comment to a previous answer that your tableView:numberOfRowsInSection
is correct, then it must be the update. If commentsArray
is nil in the first update for some reason that might explain things. Perhaps try the following:
NSAssert(commentsArray, @"commentsArray is nil");
[commentsArray addObject:newestEntry];
The assert will be ignored in a release build, so use a debug build.
Just make sure the array which you are using to update is the same as Array which you are using while reloading the Table.
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [commentsArray count];
}
If this couldn't solve your problem, please put some code over here.
精彩评论