johnbakers
johnbakers

Reputation: 24771

addEntriesFromDictionary: a true copy method?

I am trying to understand exactly what is going on with this method, as noted in the Apple docs:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html

If I create an NSMutableDicationary and use addEntriesFromDictionary: to fill it, can I do anything I want to this mutable dictionary without affecting the original immutable dictionary from where these items came?

Upvotes: 1

Views: 6969

Answers (3)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

The original dictionary will not be modified. However, if the keys or values of the original dictionary are themselves mutable in some way (e.g. they're instances of UIView or NSMutableArray) and you modify them, the changes will be reflected in the original dictionary.

To avoid that, make a deep copy of the original dictionary before adding it to the new dictionary:

NSDictionary *deepCopy = [[NSDictionary alloc] initWithDictionary: original copyItems: YES];
if (deepCopy) {
    [destination addEntriesFromDictionary: deepCopy];
    [deepCopy release];
}

Upvotes: 3

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

You can check for yourself by logging the addresses of the keys and values. My guess is that it copies the keys, as is the standard NSDictionary behavior, and simply retains the values. You can mutate the dictionary (which comprises just the key->value mappings) all you want, but if you mutate the objects that are its values, you'll be mutating those objects everywhere.

EDIT: Logging a test case as suggested indeed shows that is the behavior. The copied key will in fact be the same as the original key for the common case of an immutable string key.

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 225142

Yes, modifications you make to the new dictionary will not affect the old one. Any changes you make to the objects inside the dictionary will affect those inside the original dictionary, though. They are the same same objects, after all. As the documentation says:

Each value object from otherDictionary is sent a retain message before being added to the receiving dictionary. In contrast, each key object is copied ... and the copy is added to the receiving dictionary.

Upvotes: 3

Related Questions