使用 deleteRows 从 UITableView 中移除 Cell 时发生如下报错:

‘NSInternalInconsistencyException’, reason: ‘Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), 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).’

报错的意思就是:执行 deleteRows 后,用于 Cell 显示的数据依然是 3 条。所以正确的顺序应该是:

  1. 从数据源中删除一条数据
  2. 执行 deleteRows
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Deleted")

self.catNames.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}

参考资料