Reputation: 7484
Say I have an Entity Department that has a to-many relationship with Persons. I want to be able to search the Department Sports to see if Person Scott Olsen works there. The Person
Scott Olsen is not unique (there may be 3 Scotts working in 3 different Department
s).
How can I search the Department
Sports to find the Person
Scott Olsen that works there and not find the other Scotts?
The basic way I can think of is:
for (Person *person in sports.persons) {
if ([person.name isEqualToString:@"Scott Olsen"]) {
// found him!
}
}
Or:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY persons.name == 'Scott Olsen'"];
Department *department = [Department MR_findFirstWithPredicate:predicate];
But I'm unsure if the second returns the Scott Olsen that works in Departement
Sports. I suppose I could then check
if ([department.name isEqualToString:@"Sports"])
But it seems like there should be a better way to do it with a NSPredicate, but I can't figure it out.
Upvotes: 1
Views: 2907
Reputation: 540005
Is this what you are looking for?
NSString *name = @"Scott Olsen";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", name];
NSSet *filtered = [sports.persons filteredSetUsingPredicate:predicate];
Or (your question changed after I posted the above code):
NSString *name = @"Scott Olsen";
NSString *department = @"Sports";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@ AND department = %@",
name, department];
Person *person = [Person MR_findFirstWithPredicate:predicate];
(assuming that you have an inverse relationship "department" from Person to Department).
Upvotes: 4
Reputation: 7241
Just add second expression in your predicate:
[NSPredicate predicateWithFormat:@"name == 'Sports' && ANY persons.name == 'Scott Olsen'"];
Upvotes: 1