基于多个键从NSArray中过滤整个NSDictionaries

时间:2010-03-16 19:37:21

标签: objective-c cocoa

我有一个NSDray的NSDictionary对象,我希望能够返回一个新的NSDictionaries数组,其中每个NSDictionary都有“Area == North”(例如)。

我到目前为止找到的最接近的示例是Using NSPredicate to filter an NSArray based on NSDictionary keys,但这只返回给定键的唯一值,而不是具有该键的字典。有没有办法执行类似的操作,并返回整个字典?

2 个答案:

答案 0 :(得分:9)

NSPredicate应该可以正常工作,我试过这个:

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

有效。

答案 1 :(得分:2)

听起来很容易:

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;