过滤和NSDictionary到NSDictionary的NSArray

时间:2013-05-02 15:16:01

标签: objective-c nsarray nsdictionary

我有一个NSDictionary,其中包含大约150个锅炉制造商的钥匙。每个键的值是NSDictionary的NSArray。每个NSDictionary代表一个具有一些属性的锅炉:

NSDictionary boilerData =
{
     @"Alpha" = [{name: Boiler1, rating: 80}, {name:Boiler2, rating: 90}],
     @"Beta" = [{name: Boiler3, rating: 80}, {name:Boiler4, rating: 91}, {name:Boiler5, rating: 78}],
     ...
}

我希望能够过滤,以便我可以获得所有评级为80的锅炉。我知道我需要一个NSPredicate,但我无法弄清楚如何构建它?我发现的其他文章似乎都不符合这一要求。

1 个答案:

答案 0 :(得分:1)

NSDictionary *boilerData =
@{
  @"Alpha" : @[@{@"name": @"Boiler1", @"rating": @80}, @{@"name": @"Boiler2", @"rating": @90}],
  @"Beta" : @[@{@"name": @"Boiler3", @"rating": @98}, @{@"name": @"Boiler4", @"rating": @80}, @{@"name": @"Boiler5", @"rating": @90}]
  };

NSMutableArray *filteredArray = [[NSMutableArray alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"rating = 80"];
for (NSArray *array in [boilerData allValues]) {
    [filteredArray addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];
}
NSLog(@"all boilers with rating = 80 : %@", filteredArray);