我在UICollectionView
中显示项目列表,并且在调用回调函数时,我正在更新项目数组,并重新绘制集合,但是应用程序每次下一条消息都会崩溃:
***-[UICollectionView _endItemAnimations]中的声明失败,/ SourceCache / UIKit / UIKit-3318.16.25 / UICollectionView.m:3765
***由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“试图将第1项插入第0节,但更新后第0节中只有1项”
我正在使用的代码是:
items = [databaseManager getNewItems];
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
[self.collectionView reloadData];
} completion:^(BOOL finished) {}];
最佳答案
我通过用以下代码替换起始代码来解决此问题:
int numberOfOldItems = (int)items.count;
items = [databaseManager getNewItems];
[self.collectionView performBatchUpdates:^{
NSMutableArray *indexpatharray = [[NSMutableArray alloc]init];
for (int i = 0; i<numberOfOldItems; i++) {
[indexpatharray addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[self.collectionView deleteItemsAtIndexPaths:indexpatharray];
[indexpatharray removeAllObjects];
for (int i = 0; i<items.count; i++) {
[indexpatharray addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[self.collectionView insertItemsAtIndexPaths:indexpatharray];
} completion:nil];
代码首先要从集合视图中删除所有项目,然后再添加新项目。