Deleting the last section of a UITableView causes an exception

Running into an issue that I believe is iOS 9-related since a Google search for this error message turns up only one result from SO and it's very recent.


I'm deleting the last section in a table, and I receive the following exception:


2015-07-14 15:40:44.613 Reps[25965:4472008] *** 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'


Here is the code in my UITableViewController subclass. I tried moving self.updateDataModel() to inside beginUpdates(), but that didn't seem to make a difference.


self.updateDataModel()
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
if self.lastSection() {
  tableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
}
tableView.endUpdates()


Any idea what could be causing this?

Replies

Not a solution, but it seems that the

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int

can't give an 0 (zero) back.

Keep it to 1, even if empty prevent the crash.

#Grominet's answer is only partly correct. The error is caused whn you delete the last row of a section. Instead, you should be deleting the section - which will automatically also remove the last row:



tableView.beginUpdates()
if tableView.numberOfRowsInSection(indexPath.section) == 1{
    tableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
}else{
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
tableView.endUpdates()