简体   繁体   中英

Error after removing an object from ManagedContext and Removing cell from TableView

when I remove one row from my TableView with this code:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source

        NSError *error = nil;
        NSLog(@"Rows before deletion: %d", [[self.fetchedResultsController fetchedObjects] count]);
        NSManagedObject *obj = [self.fetchedResultsController objectAtIndexPath:indexPath];
        [self.managedContext deleteObject:obj];
        NSLog(@"Rows before save: %d", [[self.fetchedResultsController fetchedObjects] count]);
        if (![self.managedContext save:&error]) {
            NSLog(@"Error while deleting time: %s", error.localizedDescription);
        }
        NSLog(@"Rows after save: %d", [[self.fetchedResultsController fetchedObjects] count]);
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];


    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

Then I get the following Error. What could be the reason? The count of objects is everytime the same. Why the context don't get this information of the removed object. Wasn't it automatic?

The error is that the count of rows after the row deletion must be plus or minus the removed/added rows.

Thanks

After saving your context, you a have to re-execute your request to "update" your self.fetchedResultsController.

if (![self.managedContext save:&error]) {
        NSLog(@"Error while deleting time: %s", error.localizedDescription);
    }
self.fetchedResultsController = ...    
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM