Search code examples
ioscore-datanspredicate

How to perform a compound query against to many relationships in CoreData


I am looking for some assistance in understanding NSPredicates and how to query CoreData. Here is what I have:

I have two entities: 1. Capture that represents a "capture" of some data and it has a to many relationship to 2. Identity tags.

I am looking to essentially get a Set of "Identity" tags from a particular Set of "Captures". i.e. I want to know all the unique identities of name 'X' for captures that are also tagged with an id of Int 'y'.

In swift I would model this like:

let captures: [Capture]
let identities = captures.flatmap({ $0.identities }).filter({ $0.id == "y" })
let uniqueIdentitiesOfParticularType: Set<Identity> = Set(identities.flatMap({ $0.name })

Any help please?


Solution

  • First, definitely start with the Predicate Programming Guide, which covers more of this in detail. See particularly "Using Predicates with Core Data."

    Your solution is likely something along these lines if you wanted to be a bit careful about faulting:

    let request = NSFetchRequest(entityName: "Capture")
    let id = "y"
    request.predicate = NSPredicate(format: "id == %@", id)
    let identities = try context.executeFetchRequest(request) as NSArray
    let names = identities.valueForKeyPath("@distinctUnionOfObjects.name")
    

    Note that iOS 10 adds better bridges for this to Swift (you may not need as NSArray), but I haven't really explored them yet.

    For more on @distinctUnionOfObjects and its friends, see Collection Operators.