将NSMutableDictionary的值设置为另一个值

时间:2016-12-03 08:42:11

标签: ios objective-c nsdictionary setvalue

我确实发布了从服务器检索数据的请求。现在,我有一些带有某些数据的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;
    ...
}

我该怎么做?

3 个答案:

答案 0 :(得分:0)

NSArray *dates  = ...
NSArray *closes = ...

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

请注意,日期和关闭数组必须具有相同的长度

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

如果你需要2个数组,那么你需要创建字典 _productArray2&amp; _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]];
}