Search code examples
iosobjective-cnsarraynsdictionarynspredicate

NSPredicate on NSArray of NSDictionary


Imagine you have the following structure for an NSArray of NSDictionary objects:

#define kFlameText @"text"
#define kFlameRelation @"relation"


NSArray* data = @[@{kFlameText:@"TextFlame1", kFlameRelation:@"Relation1"}, @{kFlameText:@"TextFlame2", kFlameRelation:@"Relation2"}, @{kFlameText:@"TextFlame3", kFlameRelation:@"Relation3"}}

You want to use a NSPredicate to extract the dictionary located in second position in your NSArray of NSDictionary based on the NSString @"Relation2"

You tried multiple times, with you last attempt being:

NSPredicate* sortFlames = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", @"Relation2"];

But you are still not there, you still get the following error message:

Error message while testing NSPredicate

How would you make it work?


Solution

  • This predicate should do the trick:

    NSPredicate *sortFlames = [NSPredicate predicateWithFormat:@"SELF.%K CONTAINS[cd] %@", kFlameRelation, @"Relation2"];
    

    The %K is for the dynamic property name, more info here.