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.
filter ios core-data nspredicate
Cody robertson
source share