关于UITableView 刷新遇到的坑:"Invalid update"

总结一下今天遇到的坑,开发做了这么久以为对UITableview的运用已经足够熟练,不想今天当测试把这个问题丢给我的时候,我还是花费了很长时间才把这个问题解决,为此写下这篇文章,希望能帮助以后遇到同样问题的朋友。

1.表的刷新

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadData;
以上三个方法都可以对表进行刷新,不同的是,前两个可以指定刷新特定的区,或是特定的行,进行刷新,而reloadData是刷新整个表。

2.坑的描述

 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

再说一下坑的位置:

    [_tableView beginUpdates];
    [_tableView reloadSections:set
              withRowAnimation:UITableViewRowAnimationAutomatic];
    [_tableView endUpdates];
就是这几句导致的崩溃,如果换成reloadData就不会出现问题。

网上查了半天也没找到靠谱答案,这年头还是要靠自己啊。简单翻译一下大致意思是说,这个刷新无效,具体指section 0的行数无效。下面给出了具体的原因,section 0刷新前是1行,刷新后变成了0行,而在reloadSections的set里边又没有包含要刷新的section 0,故表在刷新的时候就报错了。其他类似问题大都是这类数据不一致导致的,故我们在局部刷新的时候当表数据改变的时候一定要把所有改变的区,或者是行都包含进去,才能避免崩溃。

猜你喜欢

转载自blog.csdn.net/oXiMing1/article/details/50972833