Filter all NSDictionaries from NSArray based on multiple keys

I have an NSArray of NSDictionary objects that I would like to be able to return a new array of NSDictionaries, where each NSDictionary has "Area == North" (for example).

The closest example I've found so far is Using NSPredicate to filter NSArray based on NSDictionary keys , but it just returns unique values ​​for the given key, not the dictionary that has this key. Is there a way to perform a similar operation and return the entire dictionary?

+2
objective-c cocoa
source share
2 answers

It sounds simple enough:

NSArray *unfilteredDictionaries; // however you get this... NSMutableArray *filteredDictionaries = [NSMutableArray arrayWithCapacity:[unfilteredDictionaries count]]; NSDictionary *dict; for (dict in unfilteredDictionaries) if ([[dict valueForKey:@"Area"] isEqualToString:@"North"]) [filteredDictionaries addObject:dict]; return filteredDictionaries; 
+2
source share

NSPredicate should work fine, I tried this:

 NSMutableArray *a = [NSMutableArray array]; [a addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"North", @"Area", @"North", @"Test", nil]]; [a addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"South", @"Area", @"North", @"Test", nil]]; [a addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"East", @"Area", @"North", @"Test", nil]]; NSPredicate *p = [NSPredicate predicateWithFormat:@"%K matches %@", @"Area", @"North"]; NSArray *newArray = [a filteredArrayUsingPredicate:p]; NSLog(@"newArray:%@", [newArray description]); 

He works.

+9
source share

All Articles