I'm having a problem to update a tableview if the user inserts identical items.
I think this will be easier to understand with the code.
I have an array of items that are currently shown in a table. When the user adds or deletes some items, I'm comparing the original array with the array of items to add or delete.
This is the method that compares the two arrays:
-(BOOL)compareToArray:(NSArray*)array2 blockNewItem:(void (^)(id obj))blockAddItem blockDelItem:(void (^)(id obj))blockDelItem{
BOOL equal = YES;
NSMutableArray *array2Copy = [NSMutableArray arrayWithArray:array2];
for ( id index in self ){
if ( ![array2 containsObject:index] ){
if ( blockDelItem != nil )
blockDelItem( index );
equal = NO;
}else
[array2Copy removeObject:index];
}
for ( id index in array2Copy ){
if ( blockAddItem != nil )
blockAddItem( index );
equal = NO;
}
return equal;
}
This method is called from another class that makes the update on the tableview:
[oldFields compareToArray:newFields blockNewItem:^(CustomTableItem* obj) {
[added addObject:[NSIndexPath indexPathForRow:[newFields indexOfObject:obj] inSection:0]];
} blockDelItem:^(CustomTableItem* obj) {
[removed addObject:[NSIndexPath indexPathForRow:[oldFields indexOfObject:obj] inSection:0]];
}];
[_tableView beginUpdates];
if ( removed.count > 0 ){
[_tableView deleteRowsAtIndexPaths:removed withRowAnimation:UITableViewRowAnimationFade];
}
if ( added.count > 0 ){
[_tableView insertRowsAtIndexPaths:added withRowAnimation:UITableViewRowAnimationAutomatic];
}
_arrayFields = newFields;
[_tableView endUpdates];
This works just fine if the user does not enter two identical items in the new array. In that case I'm getting an "invalid number of rows in section" error.
How to make it work in this case?