Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate problem with column name

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?

like image 648
henryeverett Avatar asked Oct 15 '10 12:10

henryeverett


2 Answers

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.

like image 187
Hoang Pham Avatar answered Sep 28 '22 01:09

Hoang Pham


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];
like image 33
henryeverett Avatar answered Sep 28 '22 02:09

henryeverett