【问题标题】:Deleting items from a UICollection but getting an "Array index out of range" error从 UICollection 中删除项目但出现“数组索引超出范围”错误
【发布时间】:2015-12-28 22:56:36
【问题描述】:

我使用 Parse 作为后端并将项目加载到 UICollectionView 中。一切正常,但我似乎无法正确删除某些项目范围。 这是我的删除功能:

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)
}

我收到错误:致命错误:数组索引超出范围 我认为这是因为随着 for 循环循环,它会丢失一个项目,但会保持原始计数。我检查以确保 self.tasks 和 indexPaths 返回我所期望的。不知道还有什么可以尝试的。 我该如何重构呢?任何帮助或方向将不胜感激。谢谢!

【问题讨论】:

    标签: ios swift parse-platform uicollectionview


    【解决方案1】:

    尝试将self.collectionView!.deleteItemsAtIndexPaths(indexPaths) 放入performBatchUpdates 的完成处理程序中。

    编辑

    您似乎在访问时试图从 self.tasks 中删除一个项目。例如,假设您的任务有 5 个项目 [A、B、C、D、E],并且您选择删除 D 和 E。在第一次迭代中,您删除索引 3(即 D)处的项目。现在任务有 4 个项目 [A,B,C,E]。在下一次迭代中,当您尝试访问索引 4 处的项目时,在上一个删除指向 E 之前,您将得到 index out of bound 错误。

    【讨论】:

    • 不幸的是,我得到了同样的错误。该错误实际上发生在 for 循环内部,因此它永远不会那么远。
    猜你喜欢
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多