I am trying to query a table using NSPredicate. Here is essentially what I'm doing:
NSNumber *value = [NSNumber numberWithInteger: 2];
NSString *columnName = @"something_id";
NSLog(@"%@ == %@", columnName, value);
NSPredicate *refQuery = [NSPredicate predicateWithFormat: @"%@ == %@", columnName, value];
NSLog prints out what I expect ("something_id == 2"), but the predicate doesn't work. However, the predicate DOES work if I change it to:
NSPredicate *refQuery = [NSPredicate predicateWithFormat: @"something_id == %@", value];
So why won't this work and how can I fix it?
The Predicate Programming Guide from Apple says:
%@ is a var arg substitution for an object value—often a string, number, or date.
%K is a var arg substitution for a key path.
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, in your case, you need to put %K as a keypath to columnName, not %@ which will be added with quotation marks:
NSPredicate *refQuery = [NSPredicate predicateWithFormat: @"%K == %@", columnName, value];
Hope this clear your doubts.
Very weird, but I think I have solved it by doing the following:
NSNumber *value = [NSNumber numberWithInteger: 2];
NSString *columnName = @"something_id";
NSString *predicate = [NSString stringWithFormat: @"%@ == %@", columnName, value];
NSPredicate *refQuery = [NSPredicate predicateWithFormat: predicate];
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