NSPredicate具有动态键和值 [英] 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.
这里是我的代码:
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];
问题是每次都返回0。我找到了问题的根源。当有静态键时,谓词看起来像这样。
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"
通过将NSString传递给谓词来放置的第一组双引号。我将如何解决这个问题?
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?
编辑:为了清楚起见,我需要它像第一种情况,这是一个工作。
For clarity, I need it to be like the first case, that is the one that works.
推荐答案
要在谓词字符串中替换键,必须使用%K
,而不是%@
:
To substitute a key in the predicate string, you have to use %K
, not %@
:
[NSPredicate predicateWithFormat:@"%K == %@", key, value];
- %@是对象值的var arg替换,通常是字符串,数字或日期。
- %K是关键路径的var arg替换。 li>
- %@ 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.
这篇关于NSPredicate具有动态键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!