Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 405
Mehul Thakkar Avatar asked Mar 02 '17 06:03

Mehul Thakkar


1 Answers

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"];
like image 112
Anbu.Karthik Avatar answered Sep 29 '22 08:09

Anbu.Karthik