今天在调试代码的时候发现程序奔溃:
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~
在iOS开发中,遇到collectionView执行performBatchUpdates时崩溃的问题,崩溃原因是批量更新后,collectionView自动reloadData导致numberOfItemsInSection等方法被调用,若数据源未同步更新,将引发数据越界。解决办法是在performBatchUpdates的闭包内确保更新数据源的数量,以避免此类错误。
1230

被折叠的 条评论
为什么被折叠?



