iOS调用reloadRowsAtIndexPaths Crash报异常NSInternalInconsiste

背景

在更新 TableView 的时候调用[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];crash掉了,报异常attempt to delete row 0 from section 0 which only contains 0 rows before the update

原因

在调用reloadRowsAtIndexPaths时,依赖于tableView先前的状态已有要更新的cell,它内部是先删除该cell,再重新创建,所以当你在原先没有该cell的状态下调用reloadRowsAtIndexPaths,会报异常你正在尝试不存在的cell。

简言之,如果你要改变tableView的cell数量,就不要调用更新局部的cell方法。

解决办法

1.使用reloadData

reloadData是完全重新加载,包括cell数量也会重新计算,不会依赖之前tableView的状态。

2.使用beginUpdates和 endUpdates(未自验证,验证者可留言)

当你在将要更改cell数量的时候都要通知tableView更新(调用[tableView beginUpdates];)

添加时通知使用方法(void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

移除时通知使用方法 (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

当你已经更改cell数量的时候都要告诉tableView更新完毕(调用[tableView endUpdates];)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容