user330885
user330885

Reputation:

UITableView and numberOfRowsInSection crash

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!

Upvotes: 2

Views: 1375

Answers (1)

Eiko
Eiko

Reputation: 25632

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.

Upvotes: 1

Related Questions