Remove object before call `deleteRowsAtIndexPaths:withRowAnimation` still generates: Invalid update: invalid number of rows in section 0

Viewed 405

I understand that this error has been posted about on SO many times before.

The problem is that the user neglects to to remove the object from their data array before calling deleteRowsAtIndexPaths:withRowAnimation. Or sometimes, they call both reloadData and then deleteRowsAtIndexPaths:withRowAnimation.

However, I do remove the object from my data source (a NSFetchedResultsController) before calling deleteRowsAtIndexPaths:withRowAnimation. And I do not call reloadData.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*Only allow deletion for collection table */
    if(_segmentedControl.selectedSegmentIndex == 1) {
        NSLog(@"delete ca");
        if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        CollectedLeaf* collectedLeaf = [collectionFetchedResultsController objectAtIndexPath:indexPath];
        LeafletPhotoUploader * leafletPhotoUploader = [[LeafletPhotoUploader alloc] init];
        leafletPhotoUploader.collectedLeaf = collectedLeaf;

        if([LeafletUserRegistration isUserRegistered]) {
            [leafletPhotoUploader deleteCollectedLeaf:collectedLeaf delegate:self];
        }


        // Delete the managed object for the given index path
        NSManagedObjectContext *context = [collectionFetchedResultsController managedObjectContext];
        [context deleteObject:[collectionFetchedResultsController objectAtIndexPath:indexPath]];

        // Save the context.
        NSError *error;
        if (![context save:&error])
        {
            NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
            NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
            if(detailedErrors != nil && [detailedErrors count] > 0)
            {
                for(NSError* detailedError in detailedErrors)
                {
                    NSLog(@"  DetailedError: %@", [detailedError userInfo]);
                }
            }
            else 
            {
                NSLog(@"  %@", [error userInfo]);
            }
        }

    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    }

}

Yet I still get this error:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

I tried to call reloadData instead of deleteRowsAtIndexPaths:withRowAnimation.

enter image description here

Though it resolves the error, the table cell isn't really deleted, which you can see by the "Collected: null" label still there: enter image description here

This viewcontroller has a segmented control, the index of which changes the data that is loaded into the table. The data is loaded from a NSFetchedResultsController

if(_segmentedControl.selectedSegmentIndex == 1) {
       /// [_table removeFromSuperview];
        _search_bar.hidden=YES;

        UIImage *btnImage2 = [UIImage imageNamed:seg2_buttonImg];
        [_left_button setImage:btnImage2 forState:UIControlStateNormal];
        NSError *error;
        [self.collectionFetchedResultsController performFetch:&error];
        [self collectionFetchedResultsController];
        collectedLeafArray = [collectionFetchedResultsController fetchedObjects];
        [_table reloadData];
    }

As such, here is my implementation of numberOfRowsInSection:

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if(_segmentedControl.selectedSegmentIndex == 0){
        id <NSFetchedResultsSectionInfo> sectionInfo = [[speciesFetchedResultsController sections] objectAtIndex:section];

        return [sectionInfo numberOfObjects];
    }
    id <NSFetchedResultsSectionInfo> sectionInfo = [[collectionFetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

EDIT: How can I update the count of collectionFetchedResultsController after deleting a row?

1 Answers

I found a solution here. Essentially I was calling deleteRowsAtIndexPaths:withRowAnimation before the data source had had time to complete the deletion.

For other people struggling with changes in respect to a UITableView, here is a delegate method to handle it and here is the Apple documentation it was taken from:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {

    UITableView *tableView = self.tableView;

    switch(type) {

        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                   withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                   withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath]
                atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                   withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                   withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}
Related