【问题标题】:Set values of NSMutableDictionary to values in another将 NSMutableDictionary 的值设置为另一个值
【发布时间】:2016-12-03 08:42:10
【问题描述】:

我确实发布了从服务器检索数据的请求。现在,我有带有某些数据的 NSDictionary。我需要在图表中显示它,所以我必须将数据转换为适当的。这是我从服务器获取的数据:

dates =     (
        "01.01.2016",
        "01.01.2016",
        "01.01.2016"
        ...) 

closes =     {
        0 =         (
            1,
            1,
            1,
            ...)
        }

我需要把它转换成这种格式:

{
    "01.01.2016" = 1;
    "01.01.2016" = 1;
    "01.01.2016" = 1;
    ...
}

我该怎么做?

【问题讨论】:

  • 你的真名是史蒂夫·乔布斯吗?

标签: ios objective-c nsdictionary setvalue


【解决方案1】:
NSArray *dates  = ...
NSArray *closes = ...

NSMutableDictionary *result = [NSMutableDictionary new];
for (int i = 0; i < dates.count; i++) {
    result[dates[i]] = closes[i];
}
NSLog(@"%@", result)

请注意,日期和结束数组的长度必须相同

【讨论】:

    【解决方案2】:

    假设 'dates' 和 closes 元素的数量相等:

    NSMutableDictionary dataOut = [NSMutableDictionary dictionary];
    for (int index = 0; index < dataIn[@"dates"].count; index++)
    {
        dataOut[dataIn[@"dates"][index]] = dataIn[@"closes"][index];
    }
    

    根据您的确定程度以及您需要此代码的防呆程度,您可能需要添加检查(和错误处理)以涵盖上述假设。

    【讨论】:

      【解决方案3】:

      如果你有 2 个数组并且你需要创建字典,那么 _productArray2 & _productArray1

       NSDictionary * productDictionary = [NSMutableDictionary dictionary];
          for (NSUInteger index =0; index < _productArray1.count; index ++) {
              [productDictionary setValue:_productArray1[index] forKey:_productArray2[index]];
          }
      

      如果你已经有一本字典想要替换它的设置值

      NSArray * allKeys = [productDictionary allKeys];
      
      for (NSUInteger index =0; index < allKeys.count; index ++) {
          [productDictionary setValue:_productArray[index] forKey:allKeys [index]];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多