Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying an NSArray with mutable copies of the original elements

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!

like image 276
Chris Avatar asked Jul 28 '09 13:07

Chris


People also ask

What is difference between NSArray and NSMutableArray?

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.

What is NSArray Objective C?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Is NSArray ordered?

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...

What is mutableCopy Objective C?

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.


1 Answers

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.

like image 80
Brian Webster Avatar answered Sep 20 '22 21:09

Brian Webster