NSRangeException when deleting last UICollectionViewCell

风格不统一 提交于 2019-12-04 06:30:07

问题


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:


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



来源:https://stackoverflow.com/questions/36234269/nsrangeexception-when-deleting-last-uicollectionviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!