NSMutableDictionary setValue:forKeyPath:设置多个键

时间:2012-08-13 15:09:11

标签: objective-c nsmutabledictionary

// populate 'project' with contents of key in `gDictRoot`
NSDictionary *project = [gDictRoot valueForKeyPath:@"root.project0"];

// modify 'project' as necessary - actual code omitted for brevity
[project setValue:[someDict valueForKey:@"foo"] forKeyPath:@"parameters.foo"];

// add 'project' to 'gDictRoot' so it isn't lost when the view is dismissed
[gDictRoot setValue:project forKeyPath:@"root.project2"];

我向project添加gDictRoot的第三行 - project0也会被修改。不知道为什么。

1 个答案:

答案 0 :(得分:2)

您看到的行为是由于project0project2都指向同一个字典实例。对其中一个的更改将始终反映在另一个中。

如果您不想要此行为,请在制作project0之前复制project2

NSMutableDictionary *project = [NSMutableDictionary
    dictionaryWithDictionary:[gDictRoot valueForKeyPath:@"root.project0"]
];