首页 > 解决方案 > 删除在 tableview 上不可见的单元格时崩溃

问题描述

我在以下行收到错误:

[self.tableView deleteRowsAtIndexPaths:@[indexpath]] withRowAnimation:UITableViewRowAnimationFade];

该 indexPath 处的单元格也是 nil ,因为由于 tableview 滚动,该表格单元格在 tableview 上不可见:

TableCell *cell = (TableCell *)[self.tableView cellForRowAtIndexPath:indexPath];

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 5 节中的行数无效。更新后现有节中包含的行数 (25) 必须等于该节中包含的行数更新前的节 (28),加上或减去从该节插入或删除的行数(0 插入,0 删除),加上或减去移入或移出该节的行数(0 移入,0 移动出去)。'

标签: iosobjective-cuitableview

解决方案


假设您要删除第 0 节中索引 5 处的项目,您的代码将如下所示,在 Swift 中

tblList.beginUpdates()
data.remove(at: 5)
tblList.deleteRows(at: [IndexPath(row: 5, section: 0)], with: .fade)
tblList.endUpdates()

Objective-C 代码看起来像这样,

[_tblList beginUpdates];
[data removeObjectAtIndex:5];
[_tblList deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:5 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[_tblList endUpdates];

推荐阅读