filternsarraynsdictionarynspredicate

Filter NSArray with NSDictionary (nested level of object) using NSPredicate ANY and IN?


I have one main array named originalListArray with multiple objects. Here is the example of object:

Example.json

I want to find that number of objects from the originalListArray, who have amenity_id matched with my filter data.

I have do this, create one predicate usign ANY not self because NSArray with NSDictionary and in that Dictionary object may have NSArray data.

This is working fine:

 NSPredicate *predicate=[NSPredicate predicateWithFormat:@"ANY amenities.amenity_id =='1')"];

This is not working:

 NSPredicate *predicate=[NSPredicate predicateWithFormat:@"ANY amenities.amenity_id in ('1','2','3')"];

So Single value can be filtered easily but when using IN oparation it crashes and the error is like this:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "ANY amenities.amenity_id in ('1','2','3')"'


Solution

  • I think it's better to pass the array as a parameter with %@ placeholder.

    [NSPredicate predicateWithFormat:@"ANY amenities.amenity_id IN %@", @[@"1",@"2",@"3"]]
    

    That way, you can create manually your array, and if you need to change it, it's easier.

    If you still want it to do it manually changing the "string format":

    [NSPredicate predicateWithFormat:@"ANY amenities.amenity_id IN {'1', '2', '3'}"]