问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/29836516/nspredicate-coredata-fetchrequest-filtered-by-array-of-dictionaries