【问题标题】:Reorder cells in UICollectionView + NSFetchedResultsController重新排序 UICollectionView + NSFetchedResultsController 中的单元格
【发布时间】:2017-06-09 10:05:17
【问题描述】:

我有一个 UICollectionView,它使用 NSFetchedResultsController 显示来自 CoreData 的实体。正如您在屏幕截图中看到的,用户可以选择多个带有边框的单元格。

我的模型基本上只有一个字符串和一个布尔值,用于通过 UICollectionView 处理选择。

var url: String
var selected: Bool
var section:Section

我实现了func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) 以支持UICollectionViewCells 的重新排序。拖放操作工作正常,但我正在努力将移动的项目保存到 CoreData。我是否必须向我的模型添加 position 属性?

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    var sourceArray = self.fetchedResultController.fetchedObjects
    let item = sourceArray?.remove(at: sourceIndexPath.item)
    sourceArray?.insert(item!, at: destinationIndexPath.row)
    coreData.saveContext()
}

我尝试直接修改fetchedResultsController.fechtedObjects,这不是工作,因为该属性是只读的。使用 UICollectionViewNSFetchedResultsController 进行拖放的最佳方式是什么。

编辑:

UICollectionView 的初始排序基于Section 模型中的索引属性。目前,节只有这个排序键,节内的项目没有。

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "section.index", ascending: false)]
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath:"section.name", cacheName: nil)

【问题讨论】:

  • 您如何对项目进行排序以在集合视图中显示它们?
  • 我已经更新了这个问题。部分的排序基于部分模型的属性。

标签: ios swift core-data uicollectionview nsfetchedresultscontroller


【解决方案1】:

正如您所发现的,您不能只告诉NSFetchedResultsController 更改其fetchedObjects 数组中对象的顺序。该数组根据您的排序描述符进行排序,并且是只读的。

所以你有两种可能的选择:

  1. 更改您在排序描述符中使用的属性,以便新的排序结果与拖放操作的结果相匹配。保存更改,NSFetchedResultsController 委托方法将被触发。您更改了顺序,您的获取结果控制器将在其 fetchedObjects 数组中反映这一点。
  2. 不要使用NSFetchedResultsController,只需进行提取并将结果保存在您自己的数组中。重新排序您自己的数组中的项目,但不要更改 Core Data 关心的任何内容。

【讨论】: