2

I'm trying to make a deep copy of an NSMutableArray whose objects are instances of a custom class similar to this:

@interface CustomParent : NSObject
@property NSInteger Id;
@property (strong, nonatomic) NSString *IdStr;
@property (weak, nonatomic) NSDate *Date; 
@property (strong, nonatomic) NSMutableArray *CustomChildren;
@property (strong, nonatomic) CustomType *Type;
@property float Value;
@end

I know there are lots of posts dealing with copying objects, but I don´t find examples for getting a complete copy of objects with collection members or properties. NSMutableArray *dstArray = [[NSMutableArray alloc] initWithArray:srcArray copyItems:YES]; raises an exception involving the copyWithZone method.

How can I do this? Thanks!

AppsDev
  • 12,319
  • 23
  • 93
  • 186

1 Answers1

13

In order to deep copy the content of the array

[[NSMutableArray alloc] initWithArray:srcArray copyItems:YES];

will send copyWithZone: to every object inside the collection. If they don't respond to this selector, you'll get a crash.

Have your CustomParent class to conform to the NSCopying protocol and you're done.

Here's some extra info on how do achieve it: Implementing NSCopying

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235