NSPredicate : CoreData fetchRequest filtered by Array of dictionaries

随声附和 提交于 2019-12-13 07:50:26

问题


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 ORs. In outline:

  1. Iterate through all elements of the array.
  2. For each element (dictionary), construct a predicate of the form:

    [NSPredicate predicateWithFormat:@"name == %@ AND city == %@",[dictionary objectForKey:@"name"], [dictionary objectForKey:@"city"]];
    
  3. Add each such predicate to a NSMutableArray (array) of predicates

  4. Build 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

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