Collectionview performBatchUpdates crash

蓝咒 提交于 2019-12-24 03:53:27

问题


I am trying to add new items to my collection view using insertItemsAtIndexPaths. My app crashes at performBatchupdate

- (void) addItems {
    NSArray *newProducts = @[@"1",@"2",@"3",@"4"];
    [self.collectionView performBatchUpdates:^{
        NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
        for (NSInteger index = self.array.count; index < (self.array.count + newProducts.count); index++) {
            [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]];
        }
        [self.array addObjectsFromArray:newProducts];
        [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
    }
                                  completion:nil];
}

Following is the crash log:

* Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:]

This Assertion happens when cell is not registered with the collectionview. I am registering my cell.


回答1:


This worked for me: If Collection view is empty reload else insertItems.

- (void)addItems {

    NSArray *newProducts = @[@"1",@"2",@"3",@"4"];
    NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];

    for (NSInteger index = self.array.count; index < (self.array.count + newProducts.count); index++) {
        [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]];
    }

    if (self.array) {
        [self.array addObjectsFromArray:newProducts];
        [self.collectionView performBatchUpdates:^{
            [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
        }
                                      completion:nil];
    }
    else {
        self.array = [[NSMutableArray alloc] initWithArray:newProducts];
        [self.collectionView reloadData];

    }
}


来源:https://stackoverflow.com/questions/25265183/collectionview-performbatchupdates-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!