NSPredicate with dynamic key and value

core-data, filter, ios, nspredicate

Solution

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.

Problem

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.

Original source