How to delete the last row of a section?
When you delete a row, and this row is the last one of its section, you need to also delete the section. Basically, you need to keep track of both the indexPaths you want to delete, which are associated to the rows, and the indexes related to the sections that needs to be removed because they no longer contain rows. You could do it as follows:
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
Each time you delete an object from your model array related to a specific section of the tableView, check if the array count is zero, in which case add an index representing the section to indexes:
[array removeObjectAtIndex:indexPath.row];
if(![array count])
[indexes addIndex: indexPath.section];
Determine all of the indexPaths related to the rows to be deleted, then update the tableView as follows:
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[tableView deleteSections:indexes withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
This worked for me and other people I suggested the approach.
Perhaps this may work for you:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [self.keys objectAtIndex:section];
NSMutableArray *rowsInSection = [self.dict objectForKey:key];
[rowsInSection removeObjectAtIndex:row];
NSUInteger rowsInSectionCount = [rowsInSection count];
if (rowsInSectionCount > 0) {
// If we still have rows in this section just delete the row
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else {
// There are no more rows in this section
[self.dict removeObjectForKey:key];
[self.keys removeObjectAtIndex:section];
NSUInteger sectionCount = [self.keys count];
if (sectionCount > 0) {
// If we still have 1 or more sections left just delete this section
[tableView deleteSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}
else {
// If there are no more rows and sections left just delete the last row
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];
}
}
}
Hope this is what you were looking for.
This one should do the trick:
// Either delete some rows within a section (leaving at least one) or the entire section.
if ([indexPath section] < 0) {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if ([indexPath section] == 0) {
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]] withRowAnimation:UITableViewRowAnimationFade];
}