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!

5
  • 1
    take a look at the NSCoding protocol : developer.apple.com/library/mac/#documentation/cocoa/reference/… Commented Jun 27, 2013 at 13:34
  • you probably mean NSCopying Commented Jun 27, 2013 at 13:37
  • @AppsDev, any luck with the proposed solution? Commented Jun 28, 2013 at 11:43
  • @GabrielePetronella I read the post you referred and it seems to work, thanks! Commented Jun 28, 2013 at 17:55
  • @LescaiIonel I tried NSCoding before and it takes a lot of time for copying many objects connected to a class. Thins NSCopying should be faster. Commented Feb 17, 2015 at 15:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.