Search code examples
iosuitableviewdelete-row

UITableView- deleting last cell in section


This is my code to delete a cell in my UITableView:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView beginUpdates];

    if([tableView numberOfRowsInSection:[indexPath section]] > 1) {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
            withRowAnimation:UITableViewRowAnimationFade];
    } else {
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]] 
            withRowAnimation:UITableViewRowAnimationFade];
    }

    [tableView endUpdates];
}

There is also some data being updated before the cell is deleted, but I'm rather sure it is being updated properly because the count of the data source's array is always one less each time a cell is deleted. This is the expected behavior. Yet for some reason, whenever I delete the last cell in a section, I get 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

It is incredibly frustrating, especially because from what I have been able to find on the Internet, I am doing this correctly. Maybe I need sleep, it's been a while. Any ideas here?

Solution:

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableIsEmpty) {
        //**this** line was the culprit- returning zero here fixed the problem
        return 0;
    } else if(section == ([tableView numberOfSections] - 1)) {
        //this is the last section- it only needs one row for the 'Delete all' button
        return 1;
    } else {
        //figure out how many rows are needed for the section
    }
}

Solution

  • Your problem lies in the implementation of your numberOfRowsInSection: method. Your deletion seems to be fine. When you've deleted the rows, I think you are failing to update the source used to return the number of rows in the numberOfRowsInSection: method. Because of the inconsistency there, you get the error. Please share that code.