我使用不同的密钥向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” );
提前感谢您的帮助。
答案 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);
}