简体   繁体   中英

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

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"

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"];

在Swift 3.0中:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM