Ios 在UICollectionView+;NSFetchedResultsController
我有一个UICollectionView,它使用NSFetchedResultsController显示CoreData中的实体。正如您在屏幕截图上所看到的,用户可以选择多个带有边框的单元格 我的模型基本上只有一个字符串和一个布尔值,用于通过UICollectionView处理选择Ios 在UICollectionView+;NSFetchedResultsController,ios,swift,core-data,uicollectionview,nsfetchedresultscontroller,Ios,Swift,Core Data,Uicollectionview,Nsfetchedresultscontroller,我有一个UICollectionView,它使用NSFetchedResultsController显示CoreData中的实体。正如您在屏幕截图上所看到的,用户可以选择多个带有边框的单元格 我的模型基本上只有一个字符串和一个布尔值,用于通过UICollectionView处理选择 var url: String var selected: Bool var section:Section 我已经实现了func collectionView(\uCollectionView:UICollec
var url: String
var selected: Bool
var section:Section
我已经实现了func collectionView(\uCollectionView:UICollectionView,moveItemAt sourceIndexPath:IndexPath,to destinationIndexPath:IndexPath)
,以支持UICollectionViewCells
的重新排序。拖放操作工作正常,但我正在努力将移动的项目保存到CoreData。我是否必须将位置属性添加到我的模型中
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
,这不是wokring,因为该属性是只读的。使用UICollectionView
和NSFetchedResultsController
进行拖放的最佳方法是什么
编辑:
UICollectionView
的初始排序基于部分
模型中的索引属性。目前,只有此分区排序键,分区内的项目没有排序键
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "section.index", ascending: false)]
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath:"section.name", cacheName: nil)
正如您所发现的,您不能仅仅告诉NSFetchedResultsController
更改其fetchedObject
数组中对象的顺序。该数组根据排序描述符进行排序,并且是只读的
因此,您有两种可能的选择:
更改排序描述符中使用的属性,以便新的排序结果与拖放操作的结果相匹配。保存更改,将触发委托方法。您已经更改了顺序,取回的结果控制器将在其fetchedObjects
数组中反映这一点
不要使用NSFetchedResultsController
,只需执行一次提取并将结果保存在您自己的数组中即可。在您自己的阵列中重新排序项目,但不要更改核心数据关心的任何内容
您如何对项目进行排序以在集合视图中显示它们?我已更新了问题。节的排序基于节模型的属性。