tGilani tGilani -4 years ago 137
iOS Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download