删除最后一个 UICollectionViewCell 时出现 NSRangeException

NSRangeException when deleting last UICollectionViewCell

我有一个包含 1 个部分的 UICollectionView。用户可以从集合中删除单元格,我使用此代码进行删除:

[self.collectionView performBatchUpdates:^{
   [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:i inSection:0]]];
   [self.media removeObjectAtIndex:i];
} completion:nil];

除了集合中的最后一个单元格外,这对每个单元格都适用,每次都会使应用程序崩溃并出现错误:Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]

NSZombies 没有向我显示堆栈跟踪,所以我在访问数组但 none 被命中的代码的每一行上都放置了一个断点,我发现这个错误是在 [=13 之后抛出的=]、numberOfSectionsInCollectionViewsizeForItemAtIndexPath,但在 numberOfItemsInSectioncellForItemAtIndexPath

之前

是什么导致了这次崩溃?我该如何调试它?

有一些类似的 SO 帖子,但是这个 2 年前的帖子没有答案 UICollectionView crash when deleting last item, and this one only solves the problem if you want to delete the whole section: Removing the last Cell in UICollectionView makes a Crash

更新,这里是崩溃前 运行 的数据源委托方法:

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(floorf(screenWidth/3), 200);
}

只需放置异常断点,您就会发现崩溃的确切位置。