在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并调用此数据)时,会出现以下错误:
*由于“NSInternalInconsistencyException”异常终止应用程序,原因是:“无效更新:第0节中的无效项目数。在更新(8)之后,现有部分中包含的项目数量必须等于更新(4)之前包含在该节中的项数,加上或减去从该节插入或删除的项目数(32插入,0删除),加上或减去移入或移出该节的项数(0移动,0移出)。”
我理解这意味着数据源没有被正确更新。但是,在查询我的self.results数组时,我会看到数据的新计数。我正在使用addObjectsFromArray在第一行中这样做。我还将旧的结果大小存储在resultsSize中。我使用这个变量将新添加的索引路径添加到arrayWithIndexPaths中。
现在,在添加/插入项时,我尝试了以下for-循环:
for (id obj in self.results),这是我现在正在使用的。它最初工作,但进一步插入崩溃。
for (UIImage *image in newData)最初也能工作,但进一步插入崩溃。
从函数的名称来看,我相信insertItemsAtIndexPaths将在没有循环的情况下在这些索引路径上插入所有项。然而,如果没有循环,应用程序在最初尝试填充数据时会崩溃。
我还尝试从resultsSize + 1循环到新的self.results计数(其中包含新的数据),并且在初始更新时也会崩溃。
对我做错了什么有什么建议吗?
谢谢,
发布于 2012-09-30 23:33:15
我在这里看到了一些不对劲的地方。首先,我不知道你为什么要使用dispatch_sync,我对GCD没有太多的经验,我无法让它在那里工作(它似乎挂起了,UI没有响应)。也许其他人能帮上忙。其次,在添加索引路径的循环中,您正在resultsSize上循环,据我所知,这是更新之前数组的大小,这不是您想要的--您希望在resultsSize启动新的索引,然后循环到resultsSize + 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];
}https://stackoverflow.com/questions/12665669
复制相似问题