1

我有下面的字典,我想访问特定国家的所有城市。所以如果我在下面选择美国,我想访问休斯顿的达拉斯。例如,我有以下功能,但不确定如何获取国家/地区的所有城市。

-(NSArray*) fetchCitiesFromLocationDictionary:(NSMutableDictionary *)locationDictionary usingCountry:(NSString *)country
{


}


{
    509f3a914d026b589ba3a090 =     {
        coordinates =         {
            latitude = "29.76429";
            longitude = "-95.3837";
        };
        country = USA;
        id = 509f3a914d026b589ba3a090;
        name = Houston;
        state = Texas;
    };
    509f3b3a4d026b589ba3a091 =     {
        coordinates =         {
            latitude = "3.138722";
            longitude = "101.686849";
        };
        country = Malaysia;
        id = 509f3b3a4d026b589ba3a091;
        name = "Kuala Lumpur";
    };
    509f475b4d026b589ba3a093 =     {
        coordinates =         {
            latitude = "32.803468";
            longitude = "-96.769879";
        };
        country = USA;
        id = 509f475b4d026b589ba3a093;
        name = Dallas;
        state = Texas;
    };
}
4

3 回答 3

1

按照我的阅读方式,您可以遍历这些值(使用NSDictionary.allValues),如果 value.country=USA,则将 value.name 添加到您的返回列表 (NSMutableArray)。

于 2012-11-13T19:53:47.207 回答
1

尝试这样的事情:

NSDictionary *dictionary = [NSDictionary dictionary];
NSMutableArray *cities = [NSMutableArray array];
for (NSDictionary *individualDictionary in dictionary)
{
    if ([[individualDictionary objectForKey:@"country"] isEqualToString:@"USA"])
        [cities addObject:[individualDictionary objectForKey:@"name"]];
}
于 2012-11-13T19:55:01.180 回答
1

两个答案都很好,但我提出了一个更好的答案(IMO:D)

1 行

id matches = [[dictOfDicts allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"country=='USA'"]];

工作示例

int main(int argc, char *argv[]) {
    @autoreleasepool {
        id dictOfDicts = @{@"1":@{@"country":@"USA", @"name":@"test"}, @"2":@{@"country":@"azUSA", @"name":@"test"}, @"3":@{@"country":@"USA", @"name":@"test"}, @"4":@{@"country":@"adsaUSA", @"name":@"test"}};

        NSLog(@"%@", [[dictOfDicts allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"country=='USA'"]]);
    }
}
于 2012-11-13T20:22:17.223 回答