Will the NSMutableDictionary objectForKey: method return a copy or the object itself?

Does the objectForKey: method of the objectForKey: class NSMutableDictionary copy of the object?

If I have an NSMutableArray stored inside an NSMutableDictionary and I make some changes (for example, adding an object) to an array that I accessed using the objectForKey: method objectForKey: dictionary, will these modifications be modified for the array stored inside the dictionary?

+4
source share
2 answers

No, it does not return a copy.

 NSMutableArray *array = [NSMutableArray new]; NSMutableDictionary *dict = [NSMutableDictionary new]; NSLog(@"local instance of array: %p", array); [dict setObject: array forKey: @"key"]; NSLog(@"returned from dictionary: %p", [dict objectForKey: @"key"]); 

Output:

 2012-09-16 14:06:36.879 Untitled 3[65591:707] local instance of array: 0x7f98f940a2f0 2012-09-16 14:06:36.884 Untitled 3[65591:707] returned from dictionary: 0x7f98f940a2f0 

The same pointer is returned to you, that is, the object was not copied.

+9
source

If you do

 [collection setObject:obj forKey:key]; 

you put this instance of an object in a collection (dictionary, array, or set).

If you want to add a copy of an object to the dictionary, you must do this

 [collection setObject:[obj copy] forKey:key]; 

In any case, the objectForKey: method always returns what you have enclosed, rather than a copy of it.

+1
source

Source: https://habr.com/ru/post/1434461/


All Articles