UICollectionView执行performBatchUpdates 奔溃

在iOS开发中,遇到collectionView执行performBatchUpdates时崩溃的问题,崩溃原因是批量更新后,collectionView自动reloadData导致numberOfItemsInSection等方法被调用,若数据源未同步更新,将引发数据越界。解决办法是在performBatchUpdates的闭包内确保更新数据源的数量,以避免此类错误。

今天在调试代码的时候发现程序奔溃:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.performBatchUpdates({ () -> Void in
                collectionView.deleteItemsAtIndexPaths([indexPath])
            }) { (finish) -> Void in
        }
    }

在执行collectionView.performBatchUpdates的时候奔溃了,但是换成普通的delete然后reloadData就没有问题,奔溃的log:

2016-01-12 17:46:23.865 LGMagicImage[2520:845924] *** Assertion failure in -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3512.30.14/UICollectionView.m:4324

解决方法:

原因是因为在执行完performBatchUpdates操作之后,collection view会自动reloadData,调用numberOfItemsInSection等方法重新布局,这时就会出现数据越界等情况,所以我们要在performBatchUpdates的block中更新numberOfItemsInSection的个数:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.performBatchUpdates({ () -> Void in
                collectionView.deleteItemsAtIndexPaths([indexPath])
                // 该函数的作用是删除对应的模型数据
               self.removeImageWithIndex(indexPath.row)
            }) { (finish) -> Void in
        }
    }

OK~

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值