NSRangeException when deleting last UICollectionVi

2019-03-03 19:36发布

I have a UICollectionView with 1 section. The user can delete cells from the collection, and I use this code for removal:

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

This works fine for every cell except for the last cell in the collection, which crashes the app every time with the error: Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]

NSZombies aren't showing me a stack trace so I put a breakpoint on every line in my code that accesses an array but none were hit, and I found that this error is thrown after deleteItemsAtIndexPaths, numberOfSectionsInCollectionView and sizeForItemAtIndexPath, but before numberOfItemsInSection and cellForItemAtIndexPath

What could be causing this crash? How can I debug it?

There are some similar SO posts, but this one from 2 years ago has no answer 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

UPDATE, here are the data source delegate methods that run before the crash:

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

1条回答
你好瞎i
2楼-- · 2019-03-03 19:46

Just put the Exceptions Breakpoint and you'll find where exactly it is crashing.

enter image description here

查看更多
登录 后发表回答