删除最后一个 UICollectionViewCell 时出现 NSRangeException [英] NSRangeException when deleting last UICollectionViewCell

查看:19
本文介绍了删除最后一个 UICollectionViewCell 时出现 NSRangeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这对除了集合中的最后一个单元格之外的每个单元格都有效,每次都会使应用程序崩溃并出现错误:由于未捕获的异常'NSRangeException'而终止应用程序,原因:'*** -[__NSArrayMobjectAtIndex:]: index 3 越界[0 .. 2]

NSZombies 没有向我显示堆栈跟踪,因此我在代码中访问数组但没有命中的每一行都放置了一个断点,我发现在 deleteItemsAtIndexPaths 之后引发了此错误,numberOfSectionsInCollectionViewsizeForItemAtIndexPath,但在 numberOfItemsInSectioncellForItemAtIndexPath

之前

什么可能导致此崩溃?如何调试?

有一些类似的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆