Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass the key to predicate as parameter in predicateWithFormat

This may sounds silly, but here is the data to predicate:

@interface Person

@property NSString *name;
@property NSString *phone;
@property NSString *address;

@end

I got an NSPredicate that will search through Person Array, search by Name. Normally, I will use it like

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

But how can I use the key (name) as a parameter? Like

NSString *key = @"name";
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%@ contains[c] %@", key, searchText];

The predicate1 works fine, but the predicate2 doesn't. The different of those 2 when I debug with lldb:

po [predicate1 predicateFormat]
name CONTAINS[c] "Eddie"

po [predicate2 predicateFormat]
"name" CONTAINS[c] "Eddie"

Question is: Can I make the predicate2 work? I want to pass the key to search (name) as a parameter... If I can, how?

like image 788
Eddie Avatar asked Oct 30 '13 04:10

Eddie


1 Answers

From the Predicate Programming Guide

When string variables are substituted into a format string using %@ , they are surrounded by quotation marks. If you want to specify a dynamic property name, use %K in the format string

So your predicate should be

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"%K contains[c] %@", key, searchText];
like image 193
Gabriele Petronella Avatar answered Sep 28 '22 10:09

Gabriele Petronella