Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

If I have a NSMutableArray stored inside a NSMutableDictionary and I make some modifications (like adding an object) to the array that I accessed with the objectForKey: method of the dictionary will those modifications be valid for the array stored inside the dictionary?

like image 935
BigLex Avatar asked Dec 27 '22 17:12

BigLex


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

You are returned the same pointer, meaning the object has not been copied.

like image 158
joerick Avatar answered May 16 '23 07:05

joerick


If you do

[collection setObject:obj forKey:key];

you're putting that object instance inside the collection (dictionary, array or set).

If you want to add a copy of an object in a dictionary, you have to do this

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

Anyway, objectForKey: method return always exactly what you put in, not a copy of it.

like image 40
DrAL3X Avatar answered May 16 '23 06:05

DrAL3X