【发布时间】:2014-06-01 18:49:27
【问题描述】:
我有三个NSArrays,我想将它们全部组合成一个NSDictionary。问题是当我遍历数组并创建字典时,它会覆盖以前的对象。最后,我的字典里只有一个对象。我究竟做错了什么?这是我的代码:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(int i=0; i<[array0 count]; i++) {
[dict setObject:[array0 objectAtIndex:i]
forKey:@"one"];
[dict setObject:[array1 objectAtIndex:i] f
orKey:@"two"];
[dict setObject:[array2 objectAtIndex:i]
forKey:@"three"];
}
也许这会澄清我的意思...... 这就是我想要的结果:
{one = array0_obj0, two = array1_obj0, three = array2_obj0},
{one = array0_obj1, two = array1_obj1, three = array2_obj1},
{one = array0_obj2, two = array1_obj2, three = array2_obj2},
etc
谢谢
【问题讨论】:
-
就像数组每个索引有一个对象一样,字典每个键有一个对象。您在循环的每次迭代中都使用键
@"one"、@"two"和@"three",因此会覆盖字典为每个这些键存储的一个对象。回到数组的类比,这相当于每次通过循环总是分配给数组的相同索引,从而覆盖之前在相同索引处的内容。 -
旁注:
[NSString stringWithFormat:@"string that has no formatting specifiers"]没有多大意义。直接使用文字字符串即可。 -
见下面的修改答案
-
这段代码为我做了。
-
code[allDevices addObjectsFromArray:[NSArray arrayWithObjects:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects: rowID, name, company, nil] forKeys:[NSArray arrayWithObjects: @"rowID", @"name" , @"公司", nil]], nil]];code
标签: ios cocoa-touch nsarray nsdictionary