[self.collectionView insertItemsAtIndexPaths:indexPaths]; crash

开发中我们有时希望直接插入或者删除cell,而不是直接reloadData.这样做可以有时避免界面闪动,做到更好的过渡。但数据某些情况下会出现下面问题

 [self.collectionView insertItemsAtIndexPaths:indexPaths];
2016-06-20 10:56:16.906 xxx[6095:1075992] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert item 36 into section 1, but there are only 36 items in section 1 after the update'
//尝试将item36插入到第1部分中,但在更新之后的第1部分,只有36项

更新UICollectionView,数据源的数据只有36个,更新插入时,item的index最大为35,36超过故异常crash。

note:更新UICollectionView,数据源和更新的cell必须对应一致。

代码类似:

//需要插入的indexPaths
      NSMutableArray *indexpaths = [NSMutableArray array];
        for (int i = oldCellCount; i < newCellCount; i++) {
            [indexpaths addObject:[NSIndexPath indexPathForItem:i inSection:1]];
        }

        NSUInteger cellNumber = [_collectionView numberOfItemsInSection:1];
        //更新后的cell数量= 更新前数量 + 需要更新的个数
        if ((cellNumber + indexpaths.count) == self.discoverEngine.contents.count && indexpaths.count > 0) {


            [_collectionView performBatchUpdates:^{
                [_collectionView insertItemsAtIndexPaths:indexpaths];


            } completion:nil];
        } else {
            [_collectionView reloadData];
        }

你可能感兴趣的:([self.collectionView insertItemsAtIndexPaths:indexPaths]; crash)