views:

28

answers:

1

Hi,

I have a problem when trying to delete rows from my UITableView: The UITableView gets the number of rows from NSMutableArray:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [alertsArray count];
}

I add objects to the NSMutableArray in this way:

- (void)saveButton:(id)sender {
[alertsArray addObject:
[self.tableView reloadData];
}

With this code I allow to delete rows:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source.
    [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [alertsArray removeObjectAtIndex:indexPath.row];
    [tableView reloadData];
}   
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}   
}

From some reason, when trying to delete rows, the application crashes.

Thanks!

A: 

You should only do

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source.
    [alertsArray removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
} 

That is, correct your model first, and then call deleteRowsAtIndexPaths:

You will find the appropriate error message in the console window, BTW.

Also, in general no need to use reloadData here, when you didn't change other things as well.

Eiko
Just to clarify, this is because the tableView deletes the row, and then checks its datasource to make sure that the number of rows it returns is less than the number of rows it had before deleting. If the number of rows it returns is equal to the number of rows it had before deleting, it will crash.
jrtc27