views:

22

answers:

2

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?

+1  A: 

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];
henrysoup
If anyone can shed some light on why this happens I would be very grateful.
henrysoup
+3  A: 

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.

sfa
FWIW you will probably want to use %K on both sides of the predicate, as integer substitutions will be erroneously wrapped in double quotes.
ImHuntingWabbits
Nope, value is not an integer, but it's an NSNumber, as you can see in the documentation, it's the right format.
sfa