[英]Deleting items from a UICollection but getting an “Array index out of range” error
I'm using Parse as a backend and loading items into a UICollectionView. 我使用Parse作为后端并将项目加载到UICollectionView中。 Everything works great but I can't seem to properly delete certain ranges of items.
一切正常,但我似乎无法正确删除某些范围的项目。 Here's my delete function:
这是我的删除功能:
func deleteButtonTapped() {
let indexPaths = collectionView!.indexPathsForSelectedItems()!
self.collectionView!.performBatchUpdates({
for index in indexPaths {
self.tasks[index.item].deleteInBackground()
self.tasks.removeAtIndex(index.item)
}
}, completion: nil)
self.collectionView!.deleteItemsAtIndexPaths(indexPaths)
}
I get the error: fatal error: Array index out of range I think this is because as the for loop cycles it loses an item but maintains the original count. 我收到错误:致命错误:数组索引超出范围我认为这是因为在for循环中,它丢失了一个项目,但保持了原始计数。 I checked to make sure self.tasks and indexPaths returns what I expect.
我检查以确保self.tasks和indexPaths返回我期望的结果。 Not sure what else to try.
不知道还有什么尝试。 How can I refactor this?
我该如何重构? Any help or direction would be much appreciated.
任何帮助或指示将不胜感激。 Thanks!
谢谢!
Try to put the self.collectionView!.deleteItemsAtIndexPaths(indexPaths)
inside the completion handler of performBatchUpdates
. 尝试将
self.collectionView!.deleteItemsAtIndexPaths(indexPaths)
放入performBatchUpdates
的完成处理程序中。
EDIT 编辑
It looks like you are attempting to remove an item from self.tasks while accessing it. 看来您正在尝试在访问self.tasks时将其删除。 Say for example your tasks have 5 items [A,B,C,D,E] and you select to delete D & E. on the first iteration you delete item at index 3 (ie D).
假设您的任务有5个项目[A,B,C,D,E],您选择删除D&E。在第一次迭代中,您删除索引3处的项目(即D)。 Now tasks have 4 items [A,B,C,E].
现在,任务有4个项目[A,B,C,E]。 On the next iteration when you try to access item at index 4, which before the previous delete pointed to E, you'll get index out of bound error.
在下一次迭代中,当您尝试访问索引4处的项目时,在上一个删除操作指向E之前,您将获得索引超出范围的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.