views:

24

answers:

1

Hi,

it is possible and rather easy to create a NSPredicate from a string that uses the contains operator, like this:

[NSPredicate predicateWithFormat:@"name contains[cd] \"Hello!\""];

I would like to create this predicate programmatically, as it can be done for comparisons with the NSComparisonPredicate. Any ideas about this?

My motivation to do it programmatically is that it's less error prone because the search strings have user input included and are not predefined.

Heinrich

+1  A: 

Sure, it's quite simple:

NSExpression * leftExpression = [NSExpression expressionForKeyPath:@"name"];
NSExpression * rightExpression = [NSExpression expressionForConstantValue:@"Hello!"];

NSComparisonPredicate * predicate = [NSComparisonPredicate predicateWithLeftExpression:leftExpression 
                                                                       rightExpression:rightExpression 
                                                                              modifier:NSDirectPredicateModifier 
                                                                                  type:NSContainsPredicateOperatorType 
                                                                               options:(NSCaseInsensitivePredicateOption | NSDiacriticInsensitivePredicateOption)];
Dave DeLong
Wow, thanks a lot. I knew there must have been a solution.
Heinrich