我已经启用了 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]'
最佳答案
想想当你删除一个元素时数组会发生什么——上面的所有元素都向下排列 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/