Eddie
Eddie

Reputation: 1941

Can I use `predicateWithSubstitutionVariables` or something similar for the key instead of the value?

Once I asked for how to pass 1 keywords to multiple keys and got this answer: Use 1 search value for multiple keywords. And then, I asked for how to pass the key as param: Pass the key as param in NSPredicate

So now, I'm curious if I can do the vice-versa: Can I pass multiple keys as param with 1 (or maybe many) search words? If yes, then how would it look like?

Some code for you guys to edit.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(($key = 'value1') 
                           @" OR ($key = 'value2')) "
                           @" AND ($key != '0') "]; 

predicate = [predicate predicateWithSubstitutionVariables:@{@"key": @"myProperty"}];

Note that in the predicate, there's a (AND !=) so I won't be able to use the IN predicate:

[NSPredicate predicateWithFormat:@"myProperty IN %@", @[@"value1", @"value2", @"value3"]];

Those are just some sample code so please don't try to fix the predicate but keep your eyes on the question: substituteVariables with the variables is the Key to filter.

Upvotes: 0

Views: 166

Answers (1)

Willeke
Willeke

Reputation: 15623

The key must be a keypath expression:

[predicate predicateWithSubstitutionVariables:@{@"key": [NSExpression expressionForKeyPath:@"myProperty"]}]

will result in predicate

(myProperty == "value1" OR myProperty == "value2") AND myProperty != "0"

Upvotes: 2

Related Questions