'Invalid update: invalid number of rows in section 0
You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:
. So, your code should look like this:
// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//when delete is tapped
[currentCart removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
You can also simplify your code a little by using the array creation shortcut @[]
:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
Swift Version --> Remove the object from your data array before you call
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Deleted")
currentCart.remove(at: indexPath.row) //Remove element from your array
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
In my case issue was that numberOfRowsInSection
was returning similar number of rows after calling tableView.deleteRows(...)
.
Since this was the required behaviour in my case, I ended up calling tableView.reloadData()
instead of tableView.deleteRows(...)
in cases where numberOfRowsInSection
will remain same after deleting a row.