I need some clarification/advice regarding modifying objects stored in mutable containers in Objective-C.
Let’s say I have an NSMutableArray called countries inside of which there are NSMutableDictionaries that store details about each country.
NSMutableArray *countries = [[NSMutableArray alloc] init];
NSMutabelDictionary *country = [[NSMutableDictionary alloc] init];
[country setObject: @"United States" forKey: @"Name"];
[countries addObject: country];
Later I want to modify a country stored in countries. I can do this either as:
[[countries objectAtIndex: 0] setObject: @"United States of America" forKey: @"Name"];
or as:
NSMutableDictionary *cnt = [countries objectAtIndex: 0];
[cnt setObject: @"United States of America" forKey: @"Name"];
[countries replaceObjectAtIndex: 0 withObject: cnt];
the result is the same. With my C++ background, I first thought that cnt would be a copy of the object that resides at position 0 in countries and after I modify it I have to put the modified object back into countries. However, array countries would still hold the updated country object even if I don’t send it the replaceObjectAtIndex message.
I would appreciate some advice on how to deal with such situations. Is it any better to explicitly replace modified objects in mutable containers with the new one, or is it completely unnecessary?
In neither case is a copy of your
NSMutableDictionarycreated. When you call[countries objectAtIndex: 0]you are getting a reference to the sameNSMutableDictionaryobject that is in thecountriesarray. Any modifications that you make to this object will therefore automatically be reflected in the instance that is returned by thecountriesarray.In short, you have two pointers to a single object instance, and modifying the contents of a mutable collection type does not generate a copied instance of the collection.