Search code examples
iosobjective-ccore-datanspredicate

NSPredicate to filter Core Data Relationship NSSet by attribute


I have a many-to-many relationship with two entities. One is Person, the other is Clubs. I want to be able to write a predicate that will find all Person entities that are in a specific Club. I also want to check that person's position attribute.

Here is what isn't working:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"position CONTAINS[cd] %@ AND IN %@", @"manager", self.clubs.people]];
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:nil];

This crashes with error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "title CONTAINS[cd] %@ AND IN %@"'

I know I am doing something wrong here, any help?


Solution

  • As pointed out by @pbasdf above, you should use self. However, the query would be much more efficient with the self clause first i.e.

    [NSPredicate predicateWithFormat:@"SELF IN %@ AND position CONTAINS[cd] %@", self.clubs.people, @"manager"];