iOS调用reloadRowsAtIndexPaths Crash报异常NSInternalInconsistencyException

来源:互联网 发布:手机取物软件 编辑:程序博客网 时间:2024/06/07 19:29

背景

在更新 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.使用beginUpdatesendUpdates(未自验证,验证者可留言)

  1. 当你在将要更改cell数量的时候都要通知tableView更新(调用[tableView beginUpdates];
  2. 添加时通知使用方法(void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
  3. 移除时通知使用方法 (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
  4. 当你已经更改cell数量的时候都要告诉tableView更新完毕(调用[tableView endUpdates];

References:
StackOverflow - Crash on reloadRowsAtIndexPath but not on reloadData
StackOverflow - reloadRowsAtIndexPaths:withRowAnimation: crashes my app

0 0
原创粉丝点击