fetching objects from core data not in a set

tomas picture tomas · May 31, 2011 · Viewed 11.9k times · Source

I'm trying to fetch objects from core data that are not in a given set, but I haven't been able to get it to work.

For instance, suppose that we have a core data entity named User, which has a few attributes such as userName, familyName, givenName, and active. Given an array of strings representing a set of usernames, we can easily fetch all the users corresponding to that list of usernames:

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"User"
                                          inManagedObjectContext:moc];
[request setEntity:entity];

NSArray *userNames = [NSArray arrayWithObjects:@"user1", @"user2", @"user3", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName IN %@", userNames];
[request setPredicate:predicate];
NSArray *users = [moc executeFetchRequest:request error:nil];

However, I want to fetch the complement of that set, i.e., I want all the users in core data that don't have the usernames specified in the userNames array. Does anyone have an idea how to approach this issue? I thought it would be simple enough to add a "NOT" in the predicate (i.e., "userName NOT IN %@"), but Xcode throws an exception saying the predicate format could not be parsed. I also tried using the predicate builder available for fetch requests with no luck. The documentation wasn't particularly helpful either. Suggestions? Comments? Thanks for all your help :)

Answer

justin picture justin · May 31, 2011

In order to find the objects that aren't in your array, all you have to do is something like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (userName IN %@)", userNames];

That should return a request of all the objects without the ones you specified