【问题标题】:Getting values from key in NSDictionary从 NSDictionary 中的键获取值
【发布时间】:2015-10-12 23:56:23
【问题描述】:

我正在使用 Edmunds API 返回某个年份的车辆制造商 JSON 字符串。

生成的 NSDictionary 如下所示:

 makes =     (
                {
            id = 200002038;
            models =   (
                { // not relevant
                }
            );
            name = Acura;
            niceName = acura;
        },
                {
            id = 200001769;
            models =             (
                { // not relevant
                }
            );
            name = "Aston Martin";
            niceName = "aston-martin";
        },

这本字典中有更多的值...如何遍历字典以检索每个“名称”值?

【问题讨论】:

    标签: ios objective-c nsdictionary


    【解决方案1】:

    我喜欢valueForKeyPath,因为你可以用它做很多事情,而且它是一个单一的解决方案。对此进行了测试,它可以在我的开发设置中使用。如果您知道您的数据是可预测的格式,那么您可以使用valueForKeyPath 做出惊人的事情。

    NSArray *makeNames = [makes valueForKeyPath:@"name"];

    关于 valueForKeyPath 的重要信息 http://nshipster.com/kvc-collection-operators/

    【讨论】:

    • 重要的是要注意,Davids 解决方案或多或少是相同的,并且在我想检查值是否存在并执行特定逻辑的复杂潜在不可预测数据集挖掘时,我通常会使用该解决方案。研究其他 valueForKeyPath 选项,例如 @sum@avg
    【解决方案2】:
    NSMutableArray *makeNames = [NSMutableArray new];
    for (NSDictionary *make in makes) {
      NSLog(@"Make name: %@", make[@"name"]);
      [makeNames addObject:make];
    }
    NSLog(@"Makes array: %@", makeNames);
    

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 1970-01-01
      • 2014-03-16
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多