I’m having trouble with insertRowsAtIndexPaths:. I’m not quite sure how it works. I watched the WWDC 2010 video on it, but I’m still getting an error. I thought I was supposed to update the model, then wrap the insertRowsAtIndexPaths: in the tableView beginUpdates and endUpdates calls. What I have is this:
self.customTableArray = (NSMutableArray *)sortedArray;
[_customTableView beginUpdates];
[tempUnsortedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[sortedArray enumerateObjectsUsingBlock:^(id sortedObj, NSUInteger sortedIdx, BOOL *sortedStop) {
if ([obj isEqualToString:sortedObj]) {
NSIndexPath *newRow = [NSIndexPath indexPathForRow:sortedIdx inSection:0];
[_customTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newRow] withRowAnimation:UITableViewRowAnimationAutomatic];
*sortedStop = YES;
}
}];
}];
[_customTableView endUpdates];
customTableArray is my model array. sortedArray is just the sorted version of that array. When I run this code when I hit my plus button to add a new row, I get this error:
Terminating 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 (2) must be equal to the number of
rows contained in that section before the update (1), plus or minus
the number of rows inserted or deleted from that section (2 inserted,
0 deleted) and plus or minus the number of rows moved into or out of
that section (0 moved in, 0 moved out).’
I’m not sure what I’m doing wrong. Thoughts? Thanks.
I’d recommend you look a little clearer at what’s actually going on in your arrays. As the error reads out, you’re telling the table view to add two rows for some reason, while it is saying it “had one row”, and then it checks with the data source after the -endUpdates method is called, and the array only has two objects in total, not the three.
In essence, your enumeration is picking up two insertions. Your array has two objects. The table had one object already. 1 existing + 2 insertions = 3 rows. Your array only has two current objects in it. What happened to the extra object.
I would expect that somewhere along the line, either your two arrays are not in sync, or your way of evaluating which is an insert has some form of error.
I hope that helps.