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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With