NSPredicate (Core Data fetch) to filter on an attribute value being present in a supplied set (list)

Posted by starbaseweb on Stack Overflow See other posts from Stack Overflow or by starbaseweb
Published on 2011-01-08T15:49:48Z Indexed on 2011/01/08 15:53 UTC
Read the original article Hit count: 122

I'm trying to create a fetch predicate that is the analog to the SQL "IN" statement, and the syntax to do so with NSPredicate escapes me.

Here's what I have so far (the relevant excerpt from my fetching routine):

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:
    @"BodyPartCategory" inManagedObjectContext:_context];
[request setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name IN %@)", 
    [RPBodyPartCategory defaultBodyPartCategoryNames]];

[request setPredicate:predicate];

The entity "BodyPartCategory" has a string attribute "name". I have a list of names (just NSString objects) in an NSArray as returned by:

[RPBodyPartCategory defaultBodyPartCategoryNames]

So let's say that array has string such as {@"Liver", @"Kidney", @"Thyroid"} ... etc.

I want to fetch all 'BodyPartCategory' instances whose name attribute matches one of the strings in the set provided (technically NSArray but I can make it an NSSet).

In SQL, this would be something like:

SELECT *
FROM   BodyPartCategories 
WHERE  name IN ('Liver', 'Kidney', 'Thyroid')

I've gone through various portions of the Predicate Programming Guide, but I don't see this simple use case covered.

Pointers/help much appreciated!

© Stack Overflow or respective owner

Related posts about list

Related posts about core-data