Copying an NSArray with mutable copies of the original elements

Chris picture Chris · Jul 28, 2009 · Viewed 8.4k times · Source

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!

Answer

Brian Webster picture Brian Webster · Jul 28, 2009

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.