· 1 min read
iOS - UITableView Delete Row w/CoreData & Animation
I found something very important that doesn’t seem well documented, when working with editable tables and CoreData. When you are using tableView:commitEditingStyle:forRowAtIndexPath: you must not actually delete the row in that method.
For example, this will crash your app with an NSInternalConsistency error:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[[self tableView] deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
It will work if you use UITableViewRowAnimationNone, but crashes with animation. If you are using CoreData, use this instead:
- (void) controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
[[self tableView] deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
That will delete the row(s) as this method is called by CoreData after whatever block you pass it happens. Your table will refresh properly and won’t have issues after this.