Using NSPredicate to filter an NSArray based on NSDictionary keys Using NSPredicate to filter an NSArray based on NSDictionary keys objective-c objective-c

Using NSPredicate to filter an NSArray based on NSDictionary keys


It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT

NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];    NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

Filtered in this case contains the dictionary.

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)


I know it's old news but to add my two cents. By default I use the commands LIKE[cd] rather than just [c]. The [d] compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d] strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name where object.name == @"voodoo" will return the object containing the name Vòódòó.

From the Apple documentation:like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.


#import <Foundation/Foundation.h>// clang -framework Foundation Siegfried.m     intmain() {    NSArray *arr = @[        @{@"1" : @"Fafner"},        @{@"1" : @"Fasolt"}    ];    NSPredicate *p = [NSPredicate predicateWithFormat:        @"SELF['1'] CONTAINS 'e'"];    NSArray *res = [arr filteredArrayUsingPredicate:p];    NSLog(@"Siegfried %@", res);    return 0;}