您的位置:首页 > 移动开发 > IOS开发

iOS调用reloadRowsAtIndexPaths Crash报异常NSInternalInconsistencyException

2016-06-27 11:31 741 查看

背景

在更新 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];


References:

StackOverflow - Crash on reloadRowsAtIndexPath but not on reloadData

StackOverflow - reloadRowsAtIndexPaths:withRowAnimation: crashes my app
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios reloadRows 异常