将单元格添加到现有的 UICollectionView(发送到不可变对象的变异方法)

Adding Cells to existing UICollectionView (mutating method sent to immutable object)

我正在尝试找到一种将单元格添加到集合中的方法,但它一直给我 "mutating method sent to immutable object" 错误。我不知道为什么。下面发布的是我正在使用的代码。

    self.artistArray = [responseObject objectForKey:@"data"];
    self.paginationArray = [responseObject objectForKey:@"pagination"];
    //NSLog(@"%@", self.paginationArray);

    if(self.firstRequest){
        [self.collectionView reloadData];
        self.firstRequest = FALSE;
    }
    else{
        NSArray *newData = [[NSArray alloc] initWithObjects:@"otherData", nil];

        [self.collectionView performBatchUpdates:^{
            int resultsSize = [self.artistArray count]; //data is the previous array of data
            [self.artistArray 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];

    }

如果你们有任何问题,请告诉我,我会尽力为您解答。

我想

[responseObject objectForKey:@"data"];

returns 不可变对象。只需添加 mutableCopy

[[responseObject objectForKey:@"data"] mutableCopy];

或者您可以清除数组并添加新对象而不是强赋值

[self.artistArray removeAllObjects];
[self.artistArray addObjectsFromArray:[responseObject objectForKey:@"data"]];

UPD

如果您尝试添加新单元格,您应该同步数据源和集合单元格。所以试试这个

self.paginationArray = [responseObject objectForKey:@"pagination"];
if(self.firstRequest){
    [self.artistArray removeAllObjects];
    [self.collectionView reloadData];
    self.firstRequest = FALSE;
}
else {
    NSArray *newData = [[NSArray alloc] initWithObjects:@"otherData", nil];

    [self.collectionView performBatchUpdates:^{
        int resultsSize = [self.artistArray count]; //data is the previous array of data
        [self.artistArray addObjectsFromArray:newData];
        [self.artistArray addObjectsFromArray:[responseObject objectForKey:@"data"]];
        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];
}