问题
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.
回答1:
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>
).
回答2:
Assuming the following model:
.. and you want to use NSPredicate
.. you could try something like:
func searchSchool(school: School, firstName: String) -> [Person] {
let request = NSFetchRequest(entityName: "Person")
let predicate = NSPredicate(format: "school == %@ && firstName == %@", school, firstName)
request.predicate = predicate
// we will perform the request on the context associated with the School NSManagedObject
guard let context = school.managedObjectContext else {
print("provided School managed object is not associated with a managed object context")
return []
}
do {
return try context.executeFetchRequest(request) as? [Person] ?? []
} catch {
return []
}
}
However, don't forget other options (like traversing the relationship and using filter
as suggested by @Mundi)
来源:https://stackoverflow.com/questions/35968378/core-data-how-to-filter-nspredicate-including-a-relationship-requirement-and-g