nor*_*r0x 4 core-data nsfetchedresultscontroller ios uicollectionview swift
我有一个 UICollectionView,它使用 NSFetchedResultsController 显示来自 CoreData 的实体。正如您在屏幕截图中看到的,用户可以选择多个标有边框的单元格。
我的模型基本上只有一个字符串和一个布尔值,用于通过 UICollectionView 处理选择。
var url: String
var selected: Bool
var section:Section
Run Code Online (Sandbox Code Playgroud)
我已经实施了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()
}
Run Code Online (Sandbox Code Playgroud)
我尝试fetchedResultsController.fechtedObjects直接修改,但这不起作用,因为该属性是只读的。使用 和 进行拖放的最佳方法是UICollectionView什么NSFetchedResultsController?
编辑:
初始排序UICollectionView基于Section模型中的索引属性。目前,各部分只有此排序键,部分内的项目没有任何排序键。
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "section.index", ascending: false)]
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath:"section.name", cacheName: nil)
Run Code Online (Sandbox Code Playgroud)
正如您所发现的,您不能只是告诉NSFetchedResultsController更改其数组中对象的顺序fetchedObjects。该数组根据您的排序描述符进行排序,并且是只读的。
所以你有两种可能的选择:
NSFetchedResultsController委托方法将触发。您已经更改了顺序,并且您的获取结果控制器将在其fetchedObjects数组中反映该顺序。NSFetchedResultsController,只需执行 fetch 并将结果保存在您自己的数组中。对您自己的数组中的项目重新排序,但不要更改 Core Data 关心的任何内容。| 归档时间: |
|
| 查看次数: |
924 次 |
| 最近记录: |