【问题标题】:UITableView and numberOfRowsInSection crashUITableView 和 numberOfRowsInSection 崩溃
【发布时间】:2010-07-05 10:09:16
【问题描述】:

尝试从 UITableView 中删除行时遇到问题: UITableView 从 NSMutableArray 中获取行数:

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

return [alertsArray count];
}

我以这种方式将对象添加到 NSMutableArray:

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

使用此代码,我允许删除行:

- (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.
}   
}

由于某种原因,当尝试删除行时,应用程序崩溃了。

谢谢!

【问题讨论】:

    标签: iphone uitableview nsmutablearray


    【解决方案1】:

    你应该只做

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

    也就是说,先修正你的模型,然后然后调用deleteRowsAtIndexPaths:

    您会在控制台窗口中找到相应的错误消息,顺便说一句。

    另外,一般来说这里不需要使用reloadData,当你没有改变其他东西的时候。

    【讨论】:

    • 澄清一下,这是因为 tableView 删除了行,然后检查它的数据源以确保它返回的行数小于删除前的行数。如果返回的行数等于删除前的行数,就会崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多