我有下面的字典,我希望能够访问特定国家/地区的所有城市。所以,如果我选择下面的美国,我想要访问达拉斯,休斯顿。例如,我有以下功能,但不知道如何获得所有国家的城市。
-(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;
};
}
答案 0 :(得分:1)
我正在阅读这个方法,您可以遍历值(使用NSDictionary.allValues
),如果是value.country = USA,则将value.name添加到返回列表(NSMutableArray)。 / p>
答案 1 :(得分: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"]];
}
答案 2 :(得分:1)
这两个答案都很好但是id提出了一个优秀的答案(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'"]]);
}
}