0

这段代码有什么问题??我正在尝试将数据从 NSArray 放入 NSMutableDictionary,但我不想先将初始 nsarray 分成两部分,然后将数据发送到 nsdcitionary。

问题是,当我 NSLog de mutabledictionary 时,它只返回 1 项,它恰好是 NSArray 中的最后一个数据。

 NSString *str = @"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:@","];

 NSMutableDictionary *dict = [NSMutableDictionary new];
for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
    [dict setObject:[arrayFinal objectAtIndex:i] forKey:@"hora"];
    [dict setObject:[arrayFinal objectAtIndex:i+1] forKey:@"preco"];

}

结果是:

2013-09-04 20:27:33.732 separa[1438:c07] {
hora = "13:30";
preco = "2.15";
}

任何帮助将不胜感激。

4

3 回答 3

1

您需要每个键指向一个值数组。像这样的东西:

NSString *str = @"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:@","];

NSMutableArray *horas = [NSMutableArray new];
NSMutableArray *precos = [NSMutableArray new];
for (int i = 0; i < [arrayFinal count]; i += 2) {
    [horas addObject:arrayFinal[i]];
    [precos addObject:arrayFinal[i + 1]];
}

NSMutableDictionary *dict = [NSMutableDictionary new];
dict[@"hora"] = horas;
dict[@"preco"] = precos;
于 2013-09-04T23:47:46.017 回答
1
for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
    [dict setObject:[arrayFinal objectAtIndex:i+1] forKey:[arrayFinal objectAtIndex:i]];
}
于 2013-09-05T00:04:56.740 回答
0

您需要将这两个(小时和价格)分开到它们自己的 NSMutableArrays 中,然后将每个数组存储为键之一,如下所示:

NSMutableArray *hora = [NSMutableArray alloc] init];
NSMutableArray *preco = [NSMutableArray alloc] init];

NSString *str = @"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:@","];

NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
for (int i = 0; i < [arrayFinal count ]; i = i + 2) 
{
    [hora addObject:[arrayFinal objectAtIndex:i];
    [preco addObject:[arrayFinal objectAtIndex:i+1];
}

[dict setObject:hora forKey:@"hora"];
[dict setObject:preco forKey:@"preco"];

可能不完全是我这样做的方式,但我认为这是您正在寻找的概念。

于 2013-09-04T23:52:32.063 回答