Search code examples
iosswiftcore-datanspredicate

How to use NSPredicate to filter objects by the element of their NSSet property in CoreData?


I have two class, one is named Folder, the other is named Entry.

In my data model, a folder would contain multiple entry, and an entry can be contained by different folders.

So each folder has a folderID to identify itself, and a relationship named entries which is used to contains Entry instances. And each entry has an inverse relationship named superFolders which points back to the folder contains it.

Now is my question. Here I get a folderID. I want to use this and NSFetchRequest to fetch all the entries contained by this special folder in Core Data. The following is the main code:

let fetchRequest = NSFetchRequest<Entry>(entityName: "Entry")
fetchRequest.predicate = NSPredicate(format: "(ANY folder in %K).folderID = %i", #keyPath(Entry.superFolders), folerID)

The format string in above code is incorrect, but it mostly explain what I mean. Since superFolders property is actually a NSSet in Core Data, I can't use superFolders.folderID == %i as the judge condition. What exactly I want is to find all the entry whose superFolder property contains any of element which its folderID property match the given folderID.

So is that possible to use NSPredicate to express what I mean to Core Data ?


Solution

  • You want:

    let fetchRequest = NSFetchRequest<Entry>(entityName: "Entry")
    fetchRequest.predicate = NSPredicate(format: "ANY superFolders.folderID = %@", folderID)
    

    See the NSPredicate reference

    If you had a more complicated match on the superFolders relationship, you would need to use SUBQUERY, but in this case a simple ANY predicate works fine.