Search code examples
iosswiftxcodecore-datanspredicate

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.


Solution

  • 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