删除集合视图单元格时应用程序崩溃

App crash when deleting collection view cells

我启用了集合视图的多选。(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),它工作正常。

想想当你删除一个元素时数组会发生什么——上面的所有元素都向下排列 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];