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?
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With