代码之家  ›  专栏  ›  技术社区  ›  Duck

iPhone:在字典内的子字典中搜索值

  •  0
  • Duck  · 技术社区  · 16 年前

    我有一本字典,我从一个词典检索。

    假设高层次字典是国家,每个子字典是国家。

    每个国家的子词典都有诸如姓名、货币、人口、国旗等关键字。

    将字典及其子元素检索到变量后,如

    NSMutableDictionary * countries = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    

    如何检查是否存在名为“欧元”的货币?

    我的意思是,我正在检查一个子分区的键中的值…有可能吗?怎么用?

    事先谢谢。

    注意:它是字典中的字典,而不是字典中的数组或数组中的字典。每个子字典都使用一个数字存储在主字典中。因此,在子字典1中可能有一个字典,其中键是,例如,法国,欧元,3000万人。

    我要看看主字典里有没有法国分册。

    2 回复  |  直到 16 年前
        1
  •  1
  •   Bryan Henry    16 年前

    使用它可以获得任何货币名为“欧元”的国家(在NSarray中)。

    NSArray *allCountries = [countries allValues];
    NSPredicate *euroPredicate = [NSPredicate predicateWithFormat:@"currency == %@", @"Euro"];
    NSArray *filteredCountries = [allCountries filteredArrayWithPredicate:euroPredicate];
    

    如果你所要做的就是检查这样一个国家是否存在,那么你只需要做一个简单的 if (filteredCountries.count > 0) { } .

    旁注:如果国家名称也存储在内部nsdictionary中(推测国家名称是外部字典键),那么我不认为顶部数据结构是nsdictionary的原因——也许外部结构的nsarray更合适?

        2
  •  1
  •   Alex Reynolds    16 年前
    NSDictionary *_currencyDict = [countries objectForKey:@"currency"];
    NSArray *_currencies = [_currencyDict allValues]; 
    NSPredicate *_currencyPredicate = [NSPredicate predicateWithFormat:@"SELF IN %@", _currencies];
    BOOL _eurosResult = [_currencyPredicate evaluateWithObject:@"euros"];
    
    if (_eurosResult)
       NSLog(@"The value 'euros' is in the 'currency' dictionary, within the 'countries' dictionary.");
    else
       NSLog(@"The value 'euros' was not found.");