开发者

UITableView and numberOfRowsInSection crash

I have a problem when trying to delete rows from my UITableView: The UIT开发者_StackOverflow社区ableView 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜