Filtering with NSPredicate, for array count of Array inside dictionary inside array

二次信任 提交于 2019-12-10 06:18:26

问题


I have Array of format as below

[
   {
      "xyz" : [Array with different values];
      ... many more keys            
   },
   {
     .. same as above dictionary
   }
   ... many more dictionaries
]

Here see, i have Main Array of dictionaries, where each dictionary have different keys, in which there is "xyz" key, whose value is again an Array. Now i want those dictionaries for which, xyz's array must have count>2.

Now i have tried with following predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"];
NSArray *filteredArray = [resultArray filteredArrayUsingPredicate:predicate];

but this is giving me error something like this, xyz is not key-value complaint for key "count"


回答1:


In this case that results in -valueForKey: @"count" being sent to each xyz instance, and xyz isn't key value coding compliant for count.

Instead, use the @count operator to evaluate the count of the collection when you want the count then use

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.@count>2"];

instead of

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"];



回答2:


In Swift 3.0:

let fileterdArray = resultArray.filtered(using: NSPredicate.init(format: "xyz.@count>%d", 2))


来源:https://stackoverflow.com/questions/42548483/filtering-with-nspredicate-for-array-count-of-array-inside-dictionary-inside-ar

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