Reputation: 4268
I want to delete a row with animation in my table view controller. I use the following code:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == .Delete) {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
let LM_ITEM = lebensmittel[indexPath.row]
managedObjectContext?.deleteObject(lebensmittel[indexPath.row])
self.DatenAbrufen()
}
}
but after press on delete, I get this error:
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 (1) must be equal to the number of rows contained in that section before the update (1), 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).'
*** First throw call stack:
(0x1856382d8 0x1973040e4 0x185638198 0x1864eced4 0x18a296e5c 0x10010e278 0x10010ef9c 0x18a2b0ea4 0x18a3a6880 0x18a0e5398 0x18a0ce474 0x18a0e4d34 0x18a0a3f54 0x18a0de82c 0x18a0ddee4 0x18a0b1120 0x18a3522b8 0x18a0af634 0x1855f0240 0x1855ef4e4 0x1855ed594 0x1855192d4 0x18ef6f6fc 0x18a116f40 0x100134420 0x1979aea08)
libc++abi.dylib: terminating with uncaught exception of type NSException
Upvotes: 9
Views: 17403
Reputation: 9148
You need to update your model before call tableView.deleteRowsAtIndexPaths(..)
like this,
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == .Delete) {
let LM_ITEM = lebensmittel[indexPath.row]
managedObjectContext?.deleteObject(lebensmittel[indexPath.row])
self.DatenAbrufen()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
Swift 5
tableView.deleteRows(at: [indexPath], with: .automatic)
Upvotes: 13
Reputation: 4590
Swift 4.2
tableView.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
Upvotes: 4
Reputation: 135
Use this for Swift 4
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
it will delete the tableView row with animation similar to the iPhone messaging application.
Upvotes: 7
Reputation: 27424
Try the following:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == .Delete) {
let LM_ITEM = lebensmittel[indexPath.row]
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
managedObjectContext?.deleteObject(LM_ITEM)
self.DatenAbrufen()
}
}
Upvotes: 2