iOS UICollectionView reloadItemsAtIndexPaths: 闪退问题修复

报错:"
attempt to delete item 1 from section 3 which only contains 1 items before the update

"

错误原因:

列表数据section 和 indexPath.row 组数或个数在动态变化过程中执行局部刷新方法闪退,局部刷新只适合列表数据稳定情况下

第一版改错:

我加了@try @catch, 认为当 try  局部刷新 失败时候 catch 直接 [self.collectionView  reloadData]做整体刷新好了

情况是确实避免了闪退,但是 整个页面大部分空白了,基本没有了视图层级,页面可滚,代理方法也不执行了。因此该方案不可行!!!

分析:reloadItemsAtIndexPaths  刷新本质依赖于当前已存在要更新的目标cell , 如果没有情况,就会闪退 . 如果存在, 在tableView/collectionView的内部是先删除该cell,再重新创建一个cell.

真正的解决方案: 

(1)获取目标indexPath

(2)预判定是否存在目标cell 

(3)存在cell再执行

UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
if (cell) {//这里使用局部刷新前判断是否存在要更新的cell
    [[self.collectionView reloadItemsAtIndexPaths:@[indexPath]];                     
} else {//没有cell如有必要刷新可使用不依赖已存在cell 和数据动态变化影响 的整体刷新方案
    [self.collectionView reloadData];
}

参考:

https://www.jianshu.com/p/7663bba767c9

https://blog.csdn.net/m0_46479005/article/details/109464408

https://blog.csdn.net/XieYupeng520/article/details/51767469

https://stackoverflow.com/questions/10844306/crash-on-reloadrowsatindexpath-but-not-on-reloaddata

https://segmentfault.com/q/1010000000245170?bd_source_light=4746641

 

posted on 2022-09-27 11:17  ACM_Someone like you  阅读(862)  评论(0编辑  收藏  举报

导航