iOS UICollectionViewController的cell的插入/删除/刷新操作

- (void)insertItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)deleteItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)reloadItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath;

- (void)performBatchUpdates:(void (^ __nullable)(void))updates completion:(void (^ __nullable)(BOOL finished))completion;

最近的一个项目中用到了UICollectionViewController, 当然也遇到很多坑, 在执行插入/删除/刷新.etc操作的过程中, 一不小心程序就会crash掉.

例: 带动画的 插入操作
/**
 数据源数组
 */
@property (nonatomic, strong) NSMutableArray *dataSource;

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 每次执行完插入操作之后,增加cell, 都会直接通过数组元素的增加直接得到刷新
    return self.dataSource.count;
}
插入操作
NSMutableArray<NSIndexPath *> *insertData 为需要插入的 NSIndexPath 对象数组
[self.collectionView performBatchUpdates:^{
    // 在执行完插入的操作之后, 紧接着会调用UICollectionViewController的数据源方法:collectionView: numberOfItemsInSection:
    [self.collectionView insertItemsAtIndexPaths:insertData];

    // 此时如果collectionView: numberOfItemsInSection:返回的数据数量没有及时刷新,程序就会crash掉
    [self.dataSource addObjectsFromArray: insertData];
} completion:^(BOOL finished) {
            
    // 在此执行插入操作完成后的代码
}];
以上操作少一步都会crash掉

插入/删除/刷新.etc操作都几乎一样, 可以举一反三了😁

总结:

在执行插入/删除/刷新.etc操作后, 一定要及时刷新数据源

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容