【问题标题】:XCode - Objective C: Deleting Table row crashXCode - 目标 C:删除表行崩溃
【发布时间】:2012-04-17 20:02:28
【问题描述】:

欢迎!我整个上午都在做这个,但没有香蕉;也许你有洞察力!

我正在使用标准的NSMutableArray

self.itemTable = [[NSMutableArray alloc]
                 initWithObjects:@"House.",
                 @"Car.",
                 @"Keys.", nil];

现在,当我在导航栏中按“编辑”并删除一行时,我收到以下 错误消息

由于未捕获的异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效更新:无效 第 0 节中的行数。包含在第 0 节中的行数 更新后的现有节(3)必须等于 更新之前该部分中包含的行 (3),加号或减号 从该部分插入或删除的行数(0 插入, 1 已删除)并加上或减去移入或移出的行数 该部分(0 移入,0 移出)。'

我将此代码用于“删除”命令:

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


[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

关于如何使删除行功能起作用的任何见解?

编辑

找到它:将以下代码行放入工作中:

[self.itemTable removeObjectAtIndex:indexPath.row];

这使得删除代码:

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

[self.itemTable removeObjectAtIndex:indexPath.row];

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

【问题讨论】:

  • 尝试在 [tableVIew deleteRowsAtIndexPaths...] 下面的 commitEditingStyle 方法中添加 [tableView reloadData] 它可能会崩溃,因为您正在修改数据源(包含数据的数组)并且您没有更新它。 . 但是话又说回来,我可能是错的,因为我没有太多经验:)

标签: xcode uitableview edit delete-row


【解决方案1】:

我遇到了同样的问题。工作后找到了解决方案。这里我的崩溃实际上是由于从数组中删除项目后调用 tableview reload 。在崩溃报告中提到,在编辑/更新部分中的 tableview 行之前和之后必须相等。

下面的代码工作正常:

 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (editingStyle == UITableViewCellEditingStyleDelete)
     {
        //add code here for when you hit delete
        [self deleteItemAtRowIndex:indexPath];
    }
}


-(void)deleteItemAtRowIndex:(NSIndexPath *)indexpath
{
[pTableDataDataArray removeObjectAtIndex:indexpath.row];

[pTableView beginUpdates];
//[self LoadTempletesData];    no need to reload, simply remove row that to is to be delete
[pTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexpath] withRowAnimation:UITableViewRowAnimationNone];
//make changes
[pTableView endUpdates];
}

希望对他人有所帮助

【讨论】:

    【解决方案2】:

    (您似乎已经注意到)您必须在插入或删除行之前更新数据源。有时你会想做一些花哨的事情,比如添加和删除行。 (我这样做是为了隐藏一部分行并显示另一部分)。如果你需要两者都做,你可以使用这个构造

    [tableView beginUpdates];
    //make changes
    [tableView endUpdates];
    

    【讨论】:

      【解决方案3】:

      记得每次在表中添加或删除内容时更新数据源,这些内容是从数据源本身获取的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        • 1970-01-01
        相关资源
        最近更新 更多