简体   繁体   中英

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

I ran into a problem with my CoreData database while trying to use NSPredicate to only fetch data that belong to a specific profile .

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?

I hope you guys can think of a solution for this problem. Thanks a lot for your help in advance.

If you have a Profile object, and wish to fetch Data objects related to it, you can use:

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

(if it's a to-many relationship), or

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

(if it's to-one).

But equally, if you have an inverse relationship (and you probably should), let's say called data , then you can use that without the need for a fetch:

let relatedData = selectedProfile.data

First of all do not name a custom class Data . There is a struct Data in the Foundation framework.

The error says that ofProfile is an NSSet so you cannot apply this predicate.

A possible solution is to search in the type of ofProfile for records which match the name and the Data relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM