Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate with dynamic key and value

I am trying to create a function that searches through my core data stack and return the amount of messages for a desired key/value.

Here is my code:

NSFetchRequest      *messagesCountRequest = [NSFetchRequest fetchRequestWithEntityName:@"Message"];
NSEntityDescription *messageCountModel    = [NSEntityDescription entityForName:@"Message" inManagedObjectContext:_mainManagedObjectContext];

[messagesCountRequest setEntity:messageCountModel];

NSPredicate *messageCountPredicate = [NSPredicate predicateWithFormat:@"%@ == %@", key, value];

[messagesCountRequest setPredicate:messageCountPredicate];

count = (int)[_mainManagedObjectContext countForFetchRequest:messagesCountRequest error:nil];

The problem is that it returns 0 every time. I have located the source of the problem. When have a static key, the predicate looks like this.

key == "value"

When I pass through a dynamic key, it looks like this

"key" == "value"

So the problem appears to be the first set of double quotes around the key that is placed by passing a NSString to the predicate. How would I fix this?

EDIT: For clarity, I need it to be like the first case, that is the one that works.

like image 924
Cody Robertson Avatar asked Jan 27 '14 17:01

Cody Robertson


1 Answers

To substitute a key in the predicate string, you have to use %K, not %@:

[NSPredicate predicateWithFormat:@"%K == %@", key, value];

From the Predicate Format String Syntax documentation:

  • %@ 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.
like image 92
Martin R Avatar answered Nov 05 '22 13:11

Martin R