开发者

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?


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];
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜