【问题标题】:UITableView Deleteing row errorUITableView删除行错误
【发布时间】:2011-03-06 14:24:13
【问题描述】:

我是 iPhone 应用程序开发的新手。所以请和我一起放轻松:)

当我得到这个错误时,我试图从 UItableView 中删除行,我不明白为什么

Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (6) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).'

这是我删除项目方法的代码

-(void)deleteItem:(NSIndexPath *)path{
Item *i = (Item *)[list objectAtIndex:path.row];
NSLog(@"Deleting item [%@]", i.iName);
int ret;

const char *sql = "delete from items where id = ?;";
if (!deleteStmt)
{ // build update statement
    if ((ret=sqlite3_prepare_v2(db, sql, -1, &deleteStmt, NULL))!=SQLITE_OK)
    {
        NSAssert1(0, @"Error building statement to delete items [%s]", sqlite3_errmsg(db));
    }
}

// bind values to statement
NSInteger n = i.iId;
sqlite3_bind_int(deleteStmt, 1, n);
// now execute sql statement
if ((ret=sqlite3_step(deleteStmt)) != SQLITE_DONE)
{
    NSAssert1(0, @"Error deleting item [%s]", sqlite3_errmsg(db));
}

// now reset bound statement to original state
sqlite3_reset(deleteStmt);

[list removeObjectAtIndex:path.row]; // remove from table
[self readTable]; // refresh array

}

这是 UITableView 的提交编辑风格

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

if (editingStyle == UITableViewCellEditingStyleDelete) {
    [appDelegate deleteItem:indexPath];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }      
}

谁能告诉我我做错了什么。据我了解,该部分中的行数未更新。我说的对吗??

提前致谢。

【问题讨论】:

  • 删除表格中的最后一个元素时不会出现此异常。我错过了什么吗? :(

标签: iphone objective-c xcode uitableview


【解决方案1】:

正如 Apple 的 iOS 表视图编程指南中所述,删除顺序是相关的:

首先从表中删除项目; 第二次将其从模型中删除。

所以你必须切换两个删除命令:


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

【讨论】:

    【解决方案2】:

    在我的谦虚看来,在尝试了同样的事情之后,看起来表格仍然认为行数没有改变,所以我隐藏了该行,看起来它对我有用。

    【讨论】:

      【解决方案3】:

      在重新查看代码后,自己想出了解决方案。问题出在

      readTable()
      

      旧数组在再次读取之前未清空。我用了

      [list removeAllObjects]
      

      清空方法。它终于奏效了。 :)

      【讨论】:

        【解决方案4】:

        我没有看到 [table reloadData];它有效吗?通常是必需的。

        【讨论】:

          猜你喜欢
          • 2018-02-28
          • 2017-03-08
          • 2017-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-05
          相关资源
          最近更新 更多