在NSDictionary中将数组添加到不同的键

时间:2015-02-25 18:31:38

标签: ios objective-c

我使用不同的密钥向NSDictionary添加数组。 这是抽象:

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];   
    for (int i = 0; i < 3; i++) {
        [myArray removeAllObjects];      
        [myArray addObject:i];
        [myArray addObject:i];   
        [myArray addObject:i];   
        [myDict setObject:myArray forKey:[NSString stringWithFormat:@“%i”, i]];
         NSLog(@"%@", myDict);
    } 

这就是我得到的输出:

i = 1

“1”=(         “1”,         “1”,         “1”,         “1”     );

i = 2

“1”=(         “2”,         “2”,         “2”,         “2”     );

“2”=(         “2”,         “2”,         “2”,         “2”     );

i = 3

“1”=(         “3”         “3”         “3”         “3”     );

“2”=(         “3”         “3”         “3”         “3”     );

“3”=(         “3”         “3”         “3”         “3”     );

但如何得到这个?:

i = 3

“1”=(         “1”,         “1”,         “1”,         “1”     );

“2”=(         “2”,         “2”,         “2”,         “2”     );

“3”=(         “3”         “3”         “3”         “3”     );

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您不能反复重复使用相同的数组。这样做:

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];   
for (int i = 0; i < 3; i++) {
    NSMutableArray *myArray = [NSMutableArray array];
    [myArray addObject:@(i)];
    [myArray addObject:@(i)];   
    [myArray addObject:@(i)];   
    [myDict setObject:myArray forKey:[NSString stringWithFormat:@"%i", i]];
     NSLog(@"%@", myDict);
} 

请注意,您无法将int值直接添加到数组中。请注意,您需要将它们包装为NSNumber个对象。

答案 1 :(得分:-1)

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i = 1; i < 4; i++) {
    NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:3];
    [myArray addObject:[NSString stringWithFormat:@"%i", i]];
    [myArray addObject:[NSString stringWithFormat:@"%i", i]];
    [myArray addObject:[NSString stringWithFormat:@"%i", i]];
    [myDict setObject:myArray forKey:[NSString stringWithFormat:@"%i", i]];
    NSLog(@"%@", myDict);
}