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   ACM_Someone like you  阅读(1081)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示