I am creating an array of dictionaries in a class. I want to return a copy of that array to any other object that asks for it. This copy that is passed to other objects needs to be modified without modifying the original.
So I am using the following in a getter method of my class that holds the "master" array:
[[NSMutableArray alloc] initWithArray:masterArray copyItems:YES];
However, this seems to make all the dictionaries inside immutable. How can I avoid this?
I think I am missing something here. Any help will be much appreciated!
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...
The mutableCopy method returns the object created by implementing NSMutableCopying protocol's mutableCopyWithZone: By sending: NSString* myString; NSMutableString* newString = [myString mutableCopy]; The return value WILL be mutable.
Another approach you could take is to use the CFPropertyListCreateDeepCopy() function (in the CoreFoundation framework), passing in kCFPropertyListMutableContainers for the mutabilityOption argument. The code would look like:
NSMutableArray* originalArray;
NSMutableArray* newArray;
newArray = (NSMutableArray*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFPropertyListRef)originalArray, kCFPropertyListMutableContainers);
This will not only create mutable copies of the dictionaries, but it would also make mutable copies of anything contained by those dictionaries recursively. Do note though that this will only work if your array of dictionaries only contains objects that are valid property lists (array, number, date, data, string, and dictionary), so this may or may not be applicable in your particular situation.
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