NSPredicate: Combine CONTAINS with IN

I don’t think that you can combine “IN” with “CONTAINS” in a predicate. But you could split the search string into words, and create a “compound predicate”:

NSString *searchString = @"John  Sm ";
NSArray *words = [searchString componentsSeparatedByString:@" "];
NSMutableArray *predicateList = [NSMutableArray array];
for (NSString *word in words) {
    if ([word length] > 0) {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"user.name CONTAINS[c] %@ OR user.firstname CONTAINS[c] %@", word, word];
        [predicateList addObject:pred];
    }
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateList];
NSLog(@"%@", predicate);

This example produces the predicate

(user.name CONTAINS[c] "John" OR user.firstname CONTAINS[c] "John") AND
(user.name CONTAINS[c] "Sm" OR user.firstname CONTAINS[c] "Sm")

which would match “John Smith”, but not “John Miller”.

Leave a Comment