NSInternalInconsistencyException tableView row del

2019-01-20 19:52发布

Swift 3.0 iOS 10.x

Using this code to try and delete a row in a table...

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        print("DELETE \(indexPath)")
        self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)


    }
}

This fails with the error message?

2017-05-29 13:36:23.843228+0200[939:576777] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (9) must be equal to the number of rows contained in that section before the update (9), 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).'

Which sounds fair enough only this is boiler plate code? I am doing little more than clicking on the red button?

enter image description here

Yes, there are 3 rows here... in my code that crashed there were 9.

What have I missed here? Printed out the returned indexPath here and indeed it was wrong, but wait I didn't set it. This method did?

DELETE [0, 3]

1条回答
女痞
2楼-- · 2019-01-20 20:32

You must delete row in your data array before deleting in tableView

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        print("DELETE \(indexPath)")
        yourArray.remove(at: indexPath.row) /* delete in data array */
        self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
    }
}
查看更多
登录 后发表回答