NSPredicate with dynamic key and value

I am trying to create a function that scans my main data stack and returns the number of messages for the 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 found the source of the problem. When there is a static key, the predicate is as follows.

 key == "value" 

When I go through the dynamic key, it looks like this:

 "key" == "value" 

So the problem is the first set of double quotes around the key, which is placed by passing the NSString to the predicate. How can i fix this?

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

+7
filter ios core-data nspredicate
source share
2 answers

To replace the key in the predicate string, you must use %K , not %@ :

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

From String Format Syntax Documentation:

  • % @ is a replacement for var arg for an object value - often a string, number, or date.
  • % K is a replacement for var arg for the key path.
+25
source share
  let predicate = NSPredicate(format: "SELF[%@] CONTAINS %@",key,value) 

It worked for me

0
source share

All Articles