- (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, 當(dāng)然也遇到很多坑, 在執(zhí)行插入/刪除/刷新.etc操作的過程中, 一不小心程序就會crash掉.
例: 帶動畫的 插入操作
/**
數(shù)據(jù)源數(shù)組
*/
@property (nonatomic, strong) NSMutableArray *dataSource;
#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
// 每次執(zhí)行完插入操作之后,增加cell, 都會直接通過數(shù)組元素的增加直接得到刷新
return self.dataSource.count;
}
插入操作
NSMutableArray<NSIndexPath *> *insertData 為需要插入的 NSIndexPath 對象數(shù)組
[self.collectionView performBatchUpdates:^{
// 在執(zhí)行完插入的操作之后, 緊接著會調(diào)用UICollectionViewController的數(shù)據(jù)源方法:collectionView: numberOfItemsInSection:
[self.collectionView insertItemsAtIndexPaths:insertData];
// 此時如果collectionView: numberOfItemsInSection:返回的數(shù)據(jù)數(shù)量沒有及時刷新,程序就會crash掉
[self.dataSource addObjectsFromArray: insertData];
} completion:^(BOOL finished) {
// 在此執(zhí)行插入操作完成后的代碼
}];
以上操作少一步都會crash掉
插入/刪除/刷新.etc操作都幾乎一樣, 可以舉一反三了??
總結(jié):
在執(zhí)行插入/刪除/刷新.etc操作后, 一定要及時刷新數(shù)據(jù)源