这段代码有什么问题?我试图将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";
}
任何帮助将不胜感激。
答案 0 :(得分: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;
答案 1 :(得分:1)
for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
[dict setObject:[arrayFinal objectAtIndex:i+1] forKey:[arrayFinal objectAtIndex:i]];
}
答案 2 :(得分: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"];
可能不完全是我做的方式,但我认为这是你正在寻找的概念。