1
// 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"];

Third line, where I add project to gDictRootproject0 also gets modified. Don't know why.

Thromordyn
  • 1,581
  • 4
  • 17
  • 45
  • 1
    What does `NSLog(@"%p %p", [gDictRoot valueForKeyPath:@"root.project0"], [gDictRoot valueForKeyPath:@"root.project2"]);` give you ? – ldiqual Aug 13 '12 at 15:12
  • `0x6b9cc10 0x6b9cc10` ... I take it I'm initializing `project` improperly? – Thromordyn Aug 13 '12 at 15:14
  • 2
    You are initializing it as a pointer to the same thing that's at `@"root.project0"` in the root dictionary. Maybe you wanted a copy? – Phillip Mills Aug 13 '12 at 15:16
  • Just got `0x6b3eb30 0x6b27d90` so that should be fixed, but `gDictRoot` is still saving `project` to both `root.project0` and `root.project2` – Thromordyn Aug 13 '12 at 16:28

1 Answers1

2

The behavior that you see is due to the fact that both project0 and project2 point to the same dictionary instance. The change to one of them will always reflect in the other one.

If you do not want this behavior, make a copy of project0 before making it project2:

NSMutableDictionary *project = [NSMutableDictionary
    dictionaryWithDictionary:[gDictRoot valueForKeyPath:@"root.project0"]
];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thought it worked. Not so much. – Thromordyn Aug 13 '12 at 16:39
  • @Thromordyn This would copy the first-level objects, but the references to the second, third, and higher-level objects would remain the same. If you need a deeper cloning, take a look at this [question](http://stackoverflow.com/q/1950361/335858) and [answer](http://stackoverflow.com/a/1950404/335858). – Sergey Kalinichenko Aug 13 '12 at 16:46
  • I see. Have to loop again. That or read from a plist, since that's what I'll end up doing eventually anyway. Thanks for the help. – Thromordyn Aug 13 '12 at 17:05