Deleting Row from TableView and coreData

2019-07-24 03:53发布

问题:

I have some problem with deleting rows from a tableView which is filled with coreData objects.

Trying to do this:

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

        if (editingStyle == UITableViewCellEditingStyleDelete) {

            [self.tableView beginUpdates];

            NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
            NSLog(@"Deleting (%@)", [managedObject valueForKey:@"original_title"]);
            [self.managedObjectContext deleteObject:managedObject];
            [self.managedObjectContext save:nil];

            [self performFetch];       
            [self.tableView endUpdates];       
        }   
    }

So, when I click the "Delete" button, the app crashes with the following Log:

    *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2872.3/UITableView.m:1254
    2013-08-13 18:39:17.624 RR_proto[1076:a0b] *** Terminating app due to uncaught exception
 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. 
 The number of sections contained in the table view after the update (1) must be equal 
to the number of sections contained in the table view before the update (2), plus or minus
 the number of sections inserted or deleted (0 inserted, 0 deleted).'
    *** First throw call stack:

I also tried to add the following line after [self.managedObjectContext save:nil]:

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

But the app crashes like before.

One more thing, everytime i start the app again after a crash through delete-action, the cell which should be deleted is really gone!

Would be very nice, if somebody can help. I know there are many questions about similar problems and I tried different things from these, without success. Thanks!

回答1:

The table view is updated automatically by the fetched results controller delegate methods when objects are added, deleted or modified.

Therefore, to remove an object, just delete it from the managed object context. Don't call beginUpdates, endUpdates, deleteRowsAtIndexPaths or performFetch:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
        [self.managedObjectContext deleteObject:managedObject];
        [self.managedObjectContext save:nil];
    }
}