views:

157

answers:

2

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

The closest example I have found so far is http://stackoverflow.com/questions/958622/using-nspredicate-to-filter-an-nsarray-based-on-nsdictionary-keys but this just returns the unique values for a given key, not the dictionary that has that key. Is there any way to perform a similar operation, and to return the entire dictionary?

+2  A: 

Sounds easy 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;
NSResponder
+2  A: 

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]);

It works.

zonble