How can I make deleteRowsAtIndexPaths: work with GenericTableViewController?

▼魔方 西西 提交于 2019-12-28 05:14:11

问题


I'm using Matt Gallagher's GenericTableViewController idea for controlling my UITableViews. My datasource is a NSFetchedResultsController.

http://cocoawithlove.com/2008/12/heterogeneous-cells-in.html

Everything is working fine, until I try to delete a cell.

I have the following code in my View Controller:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

  if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the managed object.
        NSManagedObjectContext *context = [wineryController managedObjectContext];
        [context deleteObject:[wineryController objectAtIndexPath:indexPath]];

        NSError *error;
        if (![context save:&error]) {
            // Handle the error.
        }
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }   
}

The final line crashes with the rather verbose explanation in the console:

*** 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 (5) must be equal to the number  
of rows contained in that section before the update (5), plus or minus the number  
of rows inserted or deleted from that section (0 inserted, 1 deleted).'

OK, I understand what it is saying... a row is not getting deleted (I would assume) because I'm not forwarding some message to the right place (since I have moved some code from its 'normal' location)... anyone have any idea which one? I am totally stumped on this one.


回答1:


Well, bah. I just found this answer, which is not the same, but got me headed in the right direction. I'll leave this here for anyone in the future having similar troubles.

The key is to wrap the deleteRowsAtIndexPaths with begin and end tags, and force the model to update within the same block, resulting in:

[tableView beginUpdates];
[self constructTableGroups];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
        withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];

This caused the issue to go away, and the animations to work just perfectly.



来源:https://stackoverflow.com/questions/1016200/how-can-i-make-deleterowsatindexpaths-work-with-generictableviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!