Deleting the last section of a UITableView causes

2020-04-23 07:24发布

问题:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView internal bug: unable to generate a new section map with old section count: 1 and new section count: 0'

Below is the code

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    @try {
        NSMutableArray *arrData = [dictStartDate* objectForKey:self.navigationItem.title];
        NSLog(@"Title : %@", self.navigationItem.title);
        NSLog(@"Array count : %i", (int)arrData.count);
        return arrData.count;
    }
    @catch (NSException *ex) {
        [[ProjectHandler sharedHandler]LogException:ex.name description:ex.description className:@"TodayTasksViewController" functionName:@"numberOfRowsInSection"];
        return 0;
    }
}

回答1:

I had this problem and I solved it testing if I am deleting the last row of a section, and if so instead of deleting the row, I deleted the section. I am returning 0 to the numberOfSectionsInTableView and there is no problem, the tableView is just empty.

Bellow follows the swift code I used to check if it is the last row of a section or not and the key part, which is to delete the section and not the row.

Suppose you have objects for sections in a table view like this:

var objects: [[Object]]?

Then if you are removing a row of this table with this objects you should do:

objects![indexPath.section].removeAtIndex(indexPath.row)
if (objects![indexPath.section].count == 0) {
    objects!.removeAtIndex(indexPath.section)
    tableView.deleteSections(NSIndexSet.init(index: indexPath.section), withRowAnimation: .Left)
    return //End the func and not execute the next step
}

tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left) 

Also you could use something like this to identify if it's the last row in a section:

tableView.numberOfRowsInSection(indexPath.section)


回答2:

You seem to be deleting the only section in the table. A table must have at least 1 section. You might want to check your code to check that you are not returning 0 in numberOfSectionsInTableView: