开发者

Creating a NSPredicate with a "contains[cd]" constraint programmatically

开发者 https://www.devze.com 2023-01-20 07:10 出处:网络
it is possible and rather easy to create a NSPredicate from a string that uses the contains operator, like this:

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

[NSPredicate p开发者_如何学运维redicateWithFormat:@"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


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)];
0

精彩评论

暂无评论...
验证码 换一张
取 消