开发者

Filter entire NSDictionaries out of NSArray based on multiple keys

I have an NSArray of NSDictionary objects which I would lik开发者_JAVA百科e 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 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?


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜