我有一个NSMutableDictionary:
sampleDict = [NSMutableDictionary new];
[sampleDict setObject:@"FooIndex" forKey:@"Key_1"]; // adds @"Foo"
[sampleDict setObject:@"FooOne" forKey:@"Key_2"]; // adds @"Foo"
[sampleDict setObject:@"FooTwo" forKey:@"Key_3"]; // adds @"Foo"
[sampleDict setObject:@"FoFour" forKey:@"Key_4"]; // adds @"Foo"
[sampleDict setObject:@"FooFivve" forKey:@"Key_5"]; // adds @"Foo"
我想在这里将这个词典添加到Array on Button动作这样的代码,
arraytesting = [NSMutableArray new];
- (IBAction)action:(id)sender {
[arraytesting addObject:sampleDict];
NSLog(@"Sample arraytesting>>>>> %@",arraytesting);
}
最后输出是:
(
{
"Key_1" = FooIndex;
"Key_2" = FooOne;
"Key_3" = FooTwo;
"Key_4" = FoFour;
"Key_5" = FooFivve;
}
)
但是当我需要更新字典时:
[sampleDict setObject:@"one" forKey:@"Key_1"]; // adds @"Foo"
[sampleDict setObject:@"two" forKey:@"Key_2"]; // adds @"Foo"
[sampleDict setObject:@"three" forKey:@"Key_3"]; // adds @"Foo"
[sampleDict setObject:@"FoFour" forKey:@"Key_4"]; // adds @"Foo"
[sampleDict setObject:@"FooFivve" forKey:@"Key_5"]; // adds @"Foo"
输出如下:
(
{
"Key_1" = FooIndex;
"Key_2" = FooOne;
"Key_3" = FooTwo;
"Key_4" = FoFour;
"Key_5" = FooFivve;
},
{
"Key_1" = FooIndex;
"Key_2" = FooOne;
"Key_3" = FooTwo;
"Key_4" = FoFour;
"Key_5" = FooFivve;
}
)
我希望输出如下:
(
{
"Key_1" = FooIndex;
"Key_2" = FooOne;
"Key_3" = FooTwo;
"Key_4" = FoFour;
"Key_5" = FooFivve;
},
{
"Key_1" = one;
"Key_2" = two;
"Key_3" = three;
"Key_4" = FoFour;
"Key_5" = FooFivve;
}
)
答案 0 :(得分:1)
要为数组添加对象的引用。之后,您编辑字典并再次添加引用。您可以调用copy
来创建sampleDict的新实例。
你的方法必须是这样的:
- (IBAction)action:(id)sender { [arraytesting addObject:[sampleDict copy]]; NSLog(@"Sample arraytesting>>>>> %@",arraytesting); }
答案 1 :(得分:0)
[sampleDict setObject:@"one" forKey:@"Key_1"]; // adds @"Foo"
[sampleDict setObject:@"two" forKey:@"Key_2"]; // adds @"Foo"
[sampleDict setObject:@"three" forKey:@"Key_3"]; // adds @"Foo"
[sampleDict setObject:@"FoFour" forKey:@"Key_4"]; // adds @"Foo"
[sampleDict setObject:@"FooFivve" forKey:@"Key_5"]; // adds @"Foo"
在这里,您使用相同的sampleDict参考。而不是再创建一个新的Object并添加。
smapleDict = [NSMutableArray new]
[sampleDict setObject:@"one" forKey:@"Key_1"]; // adds @"Foo"
[sampleDict setObject:@"two" forKey:@"Key_2"]; // adds @"Foo"
[sampleDict setObject:@"three" forKey:@"Key_3"]; // adds @"Foo"
[sampleDict setObject:@"FoFour" forKey:@"Key_4"]; // adds @"Foo"
[sampleDict setObject:@"FooFivve" forKey:@"Key_5"]; // adds @"Foo"
答案 2 :(得分:0)
你的词典a
是一个参考,所以你需要它的可变副本,如果你不修改原始词典,这将修改你阵列上的所有词干,所以你需要复制,修改并添加到您的数组,像这样
map
我希望这有助于你