views:

46

answers:

1

I am building a pretty complex predicate in several iterations, and want to supply the matching values right away in the predicate.

Instead of:

[NSPredicate predicateWithFormat:@"departmentName like[c] %@"];

I want to do:

NSString *str = [NSString stringWithFormat:@"departmentName like[c] '%@'", departmentName]; [NSPredicate predicateWithFormat:str];

Since this is a dumb substitution, I guess it's possible to "hack" the predicate accidently by entering garbage.

I couldn't find anything that would "magically quote" that value for me.

Reason is, that I need to build up a complex predicate in several iterations, so I have to construct a big predicate string. Templates don't work with SUBQUERY. So I need to provide the values right away in the string, since I don't want to make 20 different predicate initializations depending on how many values I have for the predicate format.

+2  A: 

Use NSComparisonPredicate directly, and bypass the predicate format issues.

NSPredicate *fetchPredicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"departmentName"]
                                                                 rightExpression:[NSExpression expressionForConstantValue:searchTerm]
                                                                        modifier:NSDirectPredicateModifier
                                                                            type:NSLikePredicateOperatorType
                                                                         options:0];

Have a read through the Predicate Programming Guide "Creating Predicates Directly in Code", and check the class reference for NSComparisonPredicate

ohhorob