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

时间:2015-07-21 22:01:21

标签: ios objective-c uicollectionview

我试图找到一种方法将单元格添加到集合中,并且它一直给我“发送到不可变对象的变异方法”错误。我不知道为什么。以下是我正在使用的代码。

    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];

    }

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

1 个答案:

答案 0 :(得分:2)

我想

[responseObject objectForKey:@"data"];

返回不可变对象。只需添加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];
}