insertItemsAtIndexPaths更新错误

dar*_*sky 3 objective-c nsarray ipad ios uicollectionview

在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];
Run Code Online (Sandbox Code Playgroud)

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

初始插入集合视图时,此代码运行正常.但是,当我在我的集​​合视图中添加/插入更多数据时(通过更新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计数(包含新数据)并且在初始更新时也崩溃.

关于我做错了什么的任何建议?

谢谢,

rde*_*mar 14

我在这里看到了一些错误.首先,我不确定你为什么要使用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];
}
Run Code Online (Sandbox Code Playgroud)