1

Does the Objective-c copy method do a deep copy of an object?

NSObject *clone = [self copy];
RoshFsk
  • 305
  • 2
  • 11
  • You may try NSKeyArchiver https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/NSKeyedArchiver_Class/Reference/Reference.html this will help. – CoolMonster Apr 01 '14 at 06:50
  • the models usually are kind of NSDictionary or NSArray. Let me know if you are looking for creating a deep copy for these data types. – Aneesh Dangayach Apr 01 '14 at 06:56

2 Answers2

3
NSObject *clone = [self copy];

Wont perform deep copy but would be a shallow copy.

You need to implement NSCopying protocol like this

//ContactCard.h
@interface ContactCard : NSObject<NSCopying>
{
    NSString* name;
    NSString* email;
}
...
-(id)copyWithZone:(NSZone *)zone;
@end

//ContactCard.m
@implementation ContactCard
...
-(id)copyWithZone:(NSZone *)zone
{
    ContactCard* cc = [[ContactCard allocWithZone:zone]init];
    cc->email = [email copy];
    cc->name = [name copy];
    return cc;
}
...
@end

You can read more on enter link description here Or refer Apple docs on NSCopying

katch
  • 820
  • 1
  • 7
  • 24
  • That's not a deep copy; it fails to copy any subclasses of ContactCard or any external resources it may access (for example: this code would not copy an instance of an AVAssetReader object, but, rather, the pointer—that's shallow, not deep). Grossly insufficient answer. – James Bush Aug 17 '16 at 08:59
-3

this might be help. For deep copy of any custom object we need to adopt NSCopying protocol in that class. How to copy an object in objective c

Community
  • 1
  • 1
virus
  • 1,203
  • 13
  • 21