gpt4 book ai didi

swift - 在 Swift Core Data 中对存储的数据模型提取进行排序

转载 作者:行者123 更新时间:2023-11-28 06:07:57 26 4
gpt4 key购买 nike

在 Core Data 中,可以使用 Xcode 将查询保存为数据模型中的提取请求。模型中似乎没有任何方法可以为结果设置排序顺序。更糟糕的是,如果您稍后尝试在代码中添加排序:

fetchRequest.sortDescriptors = [ NSSortDescriptor( key: #keyPath(Venue.name), ascending: true) ]

运行时会抛出一个错误

Can't modify a named fetch request in an immutable model.

这表明因为 fetch 是在模型中定义的,所以它现在只是只读的。

这是否实际上意味着如果您需要一个排序的结果集,则不能将获取请求存储在模型中?

[请注意,我不是在询问一般情况下如何对抓取进行排序,而是仅询问是否可以在模型中存储已排序抓取或稍后添加排序]

最佳答案

我刚遇到同样的问题。答案就在苹果自己documentation :

However, once a model is being used, it must not be changed. This is enforced at runtime—when the object manager first fetches data using a model, the whole of that model becomes uneditable. Any attempt to mutate a model or any of its sub-objects after that point causes an exception to be thrown. If you need to modify a model that is in use, create a copy, modify the copy, and then discard the objects with the old model.

要对来自 Xcode 的获取请求进行排序,请使用

func fetchRequestFromTemplate(withName name: String, substitutionVariables variables: [String : Any]) -> NSFetchRequest<NSFetchRequestResult>?

相反,因为它返回获取请求模板的副本。

我的这段代码似乎有效(到目前为止):

 guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}

let managedContext = appDelegate.persistentContainer.viewContext
let mom: NSManagedObjectModel = appDelegate.persistentContainer.managedObjectModel
let filteredFetchRequest = mom.fetchRequestFromTemplate(withName: "SetsWithNotes", substitutionVariables: ["notes" : (Any).self])
let sort = NSSortDescriptor(key: #keyPath(MaxRepSet.date), ascending: false)
filteredFetchRequest!.sortDescriptors = [sort]
do {
maxRepSetList = try managedContext.fetch(filteredFetchRequest!) as! [MaxRepSet]
print(maxRepSetList.count)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}

关于swift - 在 Swift Core Data 中对存储的数据模型提取进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47668015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com