NSFetchedResultsController: delete 1 row crashes the app

前端 未结 2 1472
名媛妹妹
名媛妹妹 2020-12-21 11:09

Deleting a row from a UITableView fed by an NSFetchedResultsController causes my app to crash.

Error is:

* Assertion failure in -[UI

相关标签:
2条回答
  • 2020-12-21 11:32

    If you want to delete a row you need to delete managedObject only.

    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [self.managedObjectContext deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
    
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {
            // handle error
        }
    }
    

    Deleting the managed object triggers the NSFetchResultController delegate methods, and they will update the tableView.

    Edit

    You should implement NSFetchResultController delegate method

    - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath{
    switch(type) {
     case NSFetchedResultsChangeDelete:
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                break;
    }
    
    
    ////
       default:
       break;
        }
    

    Because when you work with data source like NSFetchedResultsController, all changes must come from there and your table only reflects them.

    0 讨论(0)
  • 2020-12-21 11:36

    Don't call

    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    

    if you use a fetched results controller. Only delete the object with

    [self.managedObjectContext deleteObject:sd];
    

    The fetched results controller delegate method didChangeObject: is then called automatically, and that calls deleteRowsAtIndexPaths:.

    So in your case, the row was deleted twice, and that caused the exception.

    Note that you don't need beginUpdates/endUpdates here.

    0 讨论(0)
提交回复
热议问题