ios - 删除 Collection View 单元格时应用程序崩溃

标签 ios objective-c uicollectionview nsindexpath

我已经启用了 Collection View 的多选。(Xcode 7,iOS 9)

 NSArray *paths = [self.collectionView indexPathsForSelectedItems];

// data source
 for (NSIndexPath *path in paths) {
   [datasourceArray removeObjectAtIndex:path.item];
  }

// delete 
 [self.collectionView deleteItemsAtIndexPaths:paths];

我有 9 件元素。它崩溃并显示此消息:

reason: '*** -[__NSArrayM removeObjectAtIndex:]: index 8 beyond bounds [0 .. 7]'

但如果您只删除最后一个 (8),则效果很好。 enter image description here

最佳答案

想想当你删除一个元素时数组会发生什么——上面的所有元素都向下排列 1,所以元素 8 现在是元素 7,元素 7 现在是元素 6,依此类推。所以当你删除元素 6 时,不再有元素 9,所以你会得到一个越界异常。

与其在循环中调用 removeObjectAtIndex,不如使用 removeObjectsAtIndexes: 方法 -

NSArray *paths = [self.collectionView indexPathsForSelectedItems];

NSMutableIndexSet removeIndexes=[NSMutableIndexSet new];

for (NSIndexPath *path in paths) {
    [removeIndexes addIndex:path.item];
}

// delete 
[datasourceArray removeObjectAtIndexes:removeIndexes];
[self.collectionView deleteItemsAtIndexPaths:paths];

关于ios - 删除 Collection View 单元格时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678368/

相关文章:

iOS - 顶部布局指南高度问题

IOS AdaptiveView Popover 和 NavigationController : how do they work?

ios - 我是否需要某种形式的导航 Controller 来导航 View ?

c++ - 有效的 Objective-C 方法在 Objective-C++ 中无效?

ios - 未调用 UICollectionView 数据源

ios - 将 Collection View 滚动到顶部

iOS - UIButton 事件崩溃

ios - Delphi XE8 更新 1 Xcode 6.4 签名无效

ios - NSObject 的子类 - 以字节为单位的权重

ios - 使用 AFNetworking 加载图像的 UICollectionView 滚动性能