记一次崩溃记录: collectionView 的 reloadSection 意外崩溃

崩溃记录

'Invalid update: invalid number of sections. The number of sections contained in the collection view after the update (7) must be equal to the number of sections contained in the collection view before the update (9), plus or minus the number of sections inserted or deleted (1 inserted, 1 deleted).'复制代码

 问题发现. 在collectionview 中有个需求需要点击 刷新某个单独的 section , 出于性能的考虑,选择了

`self.collectionView.reloadSections(IndexSet(integer:sender.tag))`
这个方法, 但是后台监听发现有 carsh ,思索之后发现,reloadSections不仅仅是刷新当前行, 还会调用当前行之前和之后的 section 数据, 当发生数据不一致时候,就会发生 carsh

解决方案

google 一番之后 , 发现普遍推荐这个解决方案,
``` collectionView.performBatchUpdates({ UIView.performWithoutAnimation { self.collectionView.reloadSections(IndexSet(integer:sender.tag)) } }) { (success) in } ```

使用这个方法, 可以 collectionView 暂时锁定 collectionView 的数据,类似 tableview 的 beginData, 或者 enddata 方法

手动试了一下 异步删除数据,在performBatchUpdates 方法中 刷新section, 发现还是会报出崩溃
再见?, performBatchUpdates
这里推荐使用这种,
 self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout()

核心方法是这个 invalidateLayout()

将collectionViewLayout 的缓存信息销毁, 重新生成 layout

这样就不会出现, 数据不一致,然后导致崩溃的问题了.
以上是我的解决方案,要是你有更好的,可以告诉我哈 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值