NSPredicate with dynamic key and value

∥☆過路亽.° 提交于 2019-12-01 15:21:38

问题


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.


回答1:


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.



回答2:


 let predicate = NSPredicate(format: "SELF[%@] CONTAINS %@",key,value)

This worked for me



来源:https://stackoverflow.com/questions/21387925/nspredicate-with-dynamic-key-and-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!