JFS
JFS

Reputation: 3152

ios delete row from table in ViewController

I try to manage to delete a row from an UITable which is part on an UIViewController. I use the Edit button in the navigation bar. Hitting it will put the table rows in edit mode. But when a delete button in a row is pressed I get an error ...'Invalid update: invalid number of rows in section 0…. when using the following:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:YES];

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSMutableArray *work_array = [NSMutableArray arrayWithArray:self.inputValues];
        [work_array removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

What do I miss here? The Apple documentation seems to be outdated somehow. Thanks

Upvotes: 0

Views: 86

Answers (2)

Mike
Mike

Reputation: 9835

The issue you are having is that you are not directly updating your table's data source. You first create a completely new array called work_array based on your data source (I'm assuming it's self.inputValues) and then you remove an item from it, and then try to delete a row, but your tableView's data source still contains the item you intended to remove.

All you need to do is ensure that self.inputValues is a mutable array and directly remove the object at the index for that array, like this:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.inputValues removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

I hope that helps!

Upvotes: 1

rmaddy
rmaddy

Reputation: 318854

The problem is simple. You are not updating your data model properly before deleting the row from the table.

All you do is create some new array and delete a row from that. That's pointless. You need to update the same array used by the other data source methods such as numberOfRowsInSection:.

Upvotes: 2

Related Questions