Swift5中如何使用NSPredicate通过CoreData搜索关系属性的ObjectID?

How to use NSPredicate to search for ObjectID of a relationship attribute using CoreData in Swift 5?

我 运行 在尝试使用 NSPredicate 时 运行 我的 CoreData 数据库 出现问题 仅获取数据 属于特定配置文件

let request: NSFetchRequest<Data> = Data.fetchRequest()
        
let predicate = NSPredicate(format: "ofProfile.name MATCHES %@", selectedProfile.name)
request.predicate = predicate
        
do {
    let result = try context.fetch(request)
} catch {
    print("Error fetching data: \(error)")
}
! The entity Data got a ofProfile attribute which is a One - To - Many Relationship to the Profile Entity

My problem is, that the profile.name attribute is not unique since there can be multiple profiles with the same name. There is no attribute that is 100% unique.

So here's my question: Is there a way to only fetch the data of one specific profile without having a unique attribute. Maybe use the ObjectID of the active profile?

希望大家能想出解决这个问题的办法。非常感谢您的提前帮助。

首先不要命名自定义classData。 Foundation框架中有一个struct Data.

错误说 ofProfile 是一个 NSSet 所以你不能应用这个谓词。

一种可能的解决方案是在 ofProfile 类型中搜索与名称 匹配的记录 Data 关系.

如果您有一个 Profile 对象,并希望获取与之相关的 Data 个对象,您可以使用:

let predicate = NSPredicate(format: "ANY ofProfile == %@", selectedProfile)

(如果是一对多关系),或者

let predicate = NSPredicate(format: "ofProfile == %@", selectedProfile)

(如果是一对一)。

但同样地,如果你有一个反向关系(你可能应该),假设称为 data,那么你可以使用它而不需要获取:

let relatedData = selectedProfile.data