问题描述
我有一个带有1节的UICollectionView。用户可以从集合中删除单元格,并使用此代码进行删除:
[self.collectionView performBatchUpdates:^ {
[self.collectionView deleteItemsAtIndexPaths:@ [[NSIndexPath indexPathForItem:i inSection:0]]];
[self.media removeObjectAtIndex:i];
}完成:nil];
除了集合中的最后一个单元格之外,每个单元格都可以正常工作,每次都会崩溃应用程序错误:由于未捕获的异常'NSRangeException'终止应用程序,原因:'*** - [__ NSArrayM objectAtIndex:]:索引3超出边界[0 .. 2]
NSZombies没有向我显示堆栈跟踪,所以我在我的代码中的每一行都放了一个断点来访问一个数组,但没有一个被命中,我发现这个错误在 deleteItemsAtIndexPaths
, numberOfSectionsInCollectionView
和 sizeForItemAtIndexPath
之后抛出 numberOfItemsInSection
和 cellForItemAtIndexPath
可能导致此次崩溃的原因?我该怎么调试呢?
有一些类似的SO帖子,但这个2年前的帖子没有答案
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);
}
Just put the Exceptions Breakpoint and you'll find where exactly it is crashing.
这篇关于删除最后一个UICollectionViewCell时出现NSRangeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!