1
votes

I currently have a three dimensional NSMutableArray which I need to deep copy. However, it appears that the following code causes it and its contents to become immutable, since it causes NSInvalidArgumentException when I attempt to remove any objects from it.

NSMutableArray* copy = [[[NSMutableArray alloc] initWithArray:input copyItems:YES] autorelease];

How can I deep copy an array without causing it to become immutable?

2
try NSMutableArray* copy = [input mutablecopy]; - Mina Nabil

2 Answers

1
votes

From the listing,

The copy imlementation of immutable classes usually returns the same object - because it's immutable there is no need to have a "real" copy. But you don't have to worry about this.

above from http://lists.apple.com/archives/cocoa-dev/2008/May/msg00172.html

So make sure before you add your input array, convert that input array into a mutable copy and then call the method.

Code:

NSMutableArray* mutableInput = [input mutableCopy];
NSMutableArray* copy = [[[NSMutableArray alloc] initWithArray:mutableInput copyItems:YES]autorelease];
0
votes

Use NSCoding

in .h file @interface classname : NSObject

in .m file

  • (id)copyWithZone:(NSZone *)zone { }