core data how to filter (NSPredicate) including a relationship requirement and given the relationship object?

Greg picture Greg · Mar 13, 2016 · Viewed 10.7k times · Source

How would I filter (construct an NSPredicate) for the following.

  • Have a SCHOOL and PERSON entities
  • One-to-many relationship, i.e. a PERSON has one SCHOOL, SCHOOL has many PERSONs
  • Input to the filter method are (a) persons Name (e.g. all with a first name of "Tom") , and (b) the managed object of the School itself.
  • for the purposes of this question assume School has no unique attributes

So then my confusion/observations are:

  • I already have the School managed object itself, however not sure how to use this when creating the predicate?
  • But if I create the NSPredicate how do I create the relationship to the SCHOOL in any case, as there are no IDs (identifiers) linking them myself as I'm letting Core Data do this?

Preference is SWIFT (however if someone knows in Objective-C that might help me too). So what I'm trying to do again is:

  • Get all PERSON objects, for which first name = "xxx", and for which they are associated with the following SCHOOL managed object.

Answer

Mundi picture Mundi · Mar 13, 2016

The predicate would be what you expect.

NSPredicate(format: "name = %@ && school = %@", "Tom", school)

However, you can get to the person without a predicate by using the relationship in the other direction and filter.

let tom = school.persons.filter { $0.name == "Tom" }.first

(You might have to cast your NSSet to Set<Person>).