问题描述
是否可以使用字典数组创建NSPredicate?
我有以下结构:
[{name:foo,city:Paris},{name:bar,city:London}]
我想通过这些对过滤我的 NSFetchRequest
(假设属性在CoreData中具有相同的名称)
当传递数组时,我可以使用关键字 IN
。但我不知道如何使这个工作与一个字典数组。
我不认为你将能够使用 IN
,因此您需要使用一些 OR
。大纲:
- 迭代数组的所有元素。
-
(
dictionary
),构造一个形式的谓词:predicateWithFormat:@name ==%@ AND city ==%@,[dictionary objectForKey:@name],[dictionary objectForKey:@city]];
-
将每个此类谓词添加到NSMutableArray(
p>数组$
[NSCompoundPredicate orPredicateWithSubpredicates:array]
如果性能是一个问题,请考虑使用替换变量而不是格式来构建单个谓词。
Is it possible to create an NSPredicate using an array of dictionaries ?
I have a following structure :
[{ name: "foo", city:"Paris"},{name:"bar", city:"London"}]
An I want to filter my NSFetchRequest
by these pairs. (supposing the properties have the same names in CoreData)
When passing an array I can use the keyword IN
. But I don't get how make this work with an array of dictionaries.
I don't think you will be able to use IN
, so you need to use a number of OR
s. In outline:
- Iterate through all elements of the array.
For each element (
dictionary
), construct a predicate of the form:[NSPredicate predicateWithFormat:@"name == %@ AND city == %@",[dictionary objectForKey:@"name"], [dictionary objectForKey:@"city"]];
Add each such predicate to a NSMutableArray (
array
) of predicatesBuild a compound predicate from the array using:
[NSCompoundPredicate orPredicateWithSubpredicates:array]
If performance is an issue, consider building the individual predicates with substitution variables rather than with format.
这篇关于NSPredicate:CoreData fetchRequest按字典数组过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!