简体   繁体   English

UITableView和numberOfRowsInSection崩溃

[英]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: 尝试从UITableView删除行时遇到问题:UITableView从NSMutableArray获取行数:

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

return [alertsArray count];
}

I add objects to the NSMutableArray in this way: 我以这种方式将对象添加到NSMutableArray中:

- (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: 也就是说,首先更正您的模型, 然后调用deleteRowsAtIndexPaths:

You will find the appropriate error message in the console window, BTW. 您将在控制台窗口BTW中找到适当的错误消息。

Also, in general no need to use reloadData here, when you didn't change other things as well. 同样,当您也没有更改其他内容时,通常无需在此处使用reloadData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM