Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating NSPredicate dynamically by setting the key programmatically

Why does the former of following snippets work while not the latter ?

Snippet 1

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(coin_unique == %@)", [NSNumber numberWithInt:species]];

Snippet 2

// Does NOT Work
NSString *predicateText = @"coin_unique";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ == %@)", predicateText, [NSNumber numberWithInt:species]];

I have to dynamically create predicate depending upon the argument received in my method.

like image 361
atastrophic Avatar asked Mar 19 '13 16:03

atastrophic


1 Answers

coin_unique is a key, so it needs the %K format specifier:

NSString *predicateText = @"coin_unique";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", predicateText, [NSNumber numberWithInt:species]];

The format syntax is described quite well here.

like image 194
Monolo Avatar answered Nov 05 '22 20:11

Monolo