Re: How to clone a mutable dictionary
Re: How to clone a mutable dictionary
- Subject: Re: How to clone a mutable dictionary
- From: Graham Cox <email@hidden>
- Date: Fri, 24 Apr 2009 18:39:50 +1000
On 24/04/2009, at 6:35 PM, Steve Cronin wrote:
Its been a long day and maybe I'm just in need of sleep but I'm
bamboozeled...
I have an NSMutableDictionary (newThing) that is set up based on
some user defaults and current contextual data.
newThing is fine.
What I want to do is clone newThing (newThing2) and leave the
values in newThing alone.
(I'll want to come and get newThing3 sooner or later)
Everything I do causes any change I make in newThing2 to also be
made in newThing.
newThing2 = [NSMutableDictionary dictionaryWithCapacity:20];
[newThing2 setDictionary:newThing];
[newThing2 setObject:foo forKey:bar]; // at this method line
[newThing objectForKey:bar] is now foo
I've tried [newThing copy) and enumerating over [newThing allKeys]
doing a [newThing2 setObject:forKey]...
All with the same result....
How do I make an independent clone of newThing1? (XC3 / 10.5.6)
I'm sorry if this is something silly!
When a dictionary is copied, the objects it contains are not copied,
merely retained by the second dictionary. Likewise setObject:forKey
only retains the object.
You need to copy each object ("deep copy") as it is transferred to the
second dictionary.
i.e. id obj = [[newThing objectForKey:key] copy];
[newThing2 setObject:obj forKey:key];
[obj release];
--Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden