Re: how do I put an object in a dictionary, change the object but leave the dict untouched?
Re: how do I put an object in a dictionary, change the object but leave the dict untouched?
- Subject: Re: how do I put an object in a dictionary, change the object but leave the dict untouched?
- From: Ashley Clark <email@hidden>
- Date: Sat, 24 Jun 2006 14:34:11 -0500
On Jun 24, 2006, at 2:20 PM, Alan Smith wrote:
I have a NSMutableDictionary (dict1) and am using another
dictionary(dict2) as the one I change and add to dict1. Dict2 has a
set of keys that change when the user changes some text fields. Each
entry of dict1 has a dict2 in it. One would assume that there would be
no problem in changing dict2 and then adding it another time to dict1.
Well, there is. Instead of leaving the other entries the same, they
all are changed to that of what I've changed dict2 to most recently.
Example:
//Assume the dictionaries exist
[dict2 setObject: @"some object" forKey: @"object"];
[dict1 setObject: dict2 forKey: @"firstEntry"];
[dict2 setObject: @"another object" forKey: @"object"];
[dict1 setObject: dict2 forKey: @"secondEntry"];
When you call [dict1 setObject:dict2 forKey:@"secondEntry"] you're
only passing a reference to your second dictionary. So, as you've
discovered, when you change dict2 your references, still pointing to
dict2, are reflecting your changes.
If you need the whole dict2 to be assigned for each key of dict1 then
as far as I know there's no other way than to pass an autoreleased
copy of dict2 to your setObject call ([[dict2 copy] autorelease] in
lieu of dict2). But this will have the side effect of creating a new
dictionary for each key of dict1.
It might be helpful to know more of what it is you're trying to do.
Ashley Clark
After the first time I add dict2 to dict1, dict1 will have a
dictionary with "some object" in it. The second time I add dict2 to
dict1, dict1 will have two dictionaries in it. But instead of a
dictionary with "some object" and another with "another object" it
will contain two dictionaries with "another object" in both.
I don't want to fill memory by creating another dictionary for each
time the user changes the text fields. What do I do?
Thanks, Alan
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden