insertItemsAtIndexPaths更新错误

在UICollectionView中,我正在尝试使用performBatchUpdates:completion来更新我的网格视图。 我的数据源数组是self.results

这是我的代码:

 dispatch_sync(dispatch_get_main_queue(), ^{ [self.collectionView performBatchUpdates:^{ int resultsSize = [self.results count]; [self.results addObjectsFromArray:newData]; NSMutableArray *arrayWithIndexPaths = [NSMutableArray array]; if (resultsSize == 0) { [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:0]]; } else { for (int i = 0; i < resultsSize; i++) { [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:resultsSize + i inSection:0]]; } } for (id obj in self.results) [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths]; } completion:nil]; 

我有什么/我在做什么的解释:

当初始插入集合视图完成时,此代码运行良好。 但是,当我添加/插入更多的数据到我的集合视图(通过更新self.results并调用这个),这给出了以下错误:

*由于未捕获的exception'NSInternalInconsistencyException'而终止应用程序,原因:'无效的更新:部分0中的项目数目无效。更新后(8)的现有部分中包含的项目数量必须等于(4)中的该部分加或减该部分中插入或删除的项目的数目(插入32个,删除0个),加上或减去移入或移出该部分的项目的数目(移入0,0搬出)。'

我知道这意味着数据源没有正确更新。 但是,查询我的self.results数组时,我看到了新的数据。 我正在使用addObjectsFromArray在第一行做到这addObjectsFromArray 。 我还将旧的结果大小存储在resultsSize 。 我使用该variables将新添加的索引path添加到arrayWithIndexPaths

现在,当添加/插入项目时,我尝试了以下for-loop:

for (id obj in self.results)这就是我现在使用的。 它起初工作,但进一步插入崩溃。

for (UIImage *image in newData)最初工作,但进一步插入崩溃。

从函数的名字,我相信insertItemsAtIndexPaths将插入所有项目在这些索引path没有循环。 但是,如果没有循环,应用程序在最初尝试填充数据时会崩溃。

我也尝试从resultsSize + 1循环,直到新self.results计数(其中包含新的数据),并在初始更新时也崩溃。

任何关于我在做什么的错误?

谢谢,

我看到这里有几个错误。 首先,我不确定你为什么使用dispatch_sync,我没有太多的GCD经验,我不能使它在那里工作(它似乎挂起,用户界面没有响应)。 也许别人可以帮忙。 其次,在添加索引path的循环中,您正在循环播放resultsSize,据我所知,它是更新之前数组的大小,这不是您想要的 – 您希望在resultsSize并循环到resultSize + newData.count。 最后,当你调用insertItemsAtIndexPaths时,你想要做一次,而不是循环。 我试过这个,它更新集合视图(我没有尝试从头收集视图):

 -(void)addNewCells { [self.collectionView performBatchUpdates:^{ int resultsSize = [self.results count]; [self.results addObjectsFromArray:newData]; NSMutableArray *arrayWithIndexPaths = [NSMutableArray array]; for (int i = resultsSize; i < resultsSize + newData.count; i++) { [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]]; } [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths]; } completion:nil]; }