直接写代码:
头文件:
Member类,实现了深拷贝。
VIPMember类,是Member的子类,继承了Member的深拷贝协议。但VIP需要实现copyWithZone函数来实现拷贝。
@interface Member : NSObject<NSCopying>{ NSString *_name; } @property(nonatomic, retain)NSString *name; @end @interface VIPMember : Member { NSString *_vipPhone; } @property (nonatomic, retain)NSString *vipPhone; @end
@implementation Member @synthesize name=_name; - (NSString*)description{ return [NSString stringWithFormat:@"<Member>{name:%@}", self.name]; } - (void)dealloc{ [_name release]; } - (id)copyWithZone:(NSZone *)zone{ Member * member = [[self class] allocWithZone:zone]; member.name = _name; return member; } @end @implementation VIPMember @synthesize vipPhone=_vipPhone; - (NSString*)description{ NSString * str = [NSString stringWithFormat:@"<VIPMember>{member:%@,vipPhone:%@}",[super description], self.vipPhone]; return str; } - (void)dealloc{ [_vipPhone release]; [super dealloc]; } - (id)copyWithZone:(NSZone *)zone{ VIPMember * vipMember = [super copyWithZone:zone]; vipMember.vipPhone = _vipPhone; return vipMember; } @end
调用的方法:
VIPMember * member1 = [[VIPMember alloc] init]; member1.name = @"wang"; member1.vipPhone = @"13422223333"; VIPMember * member2 = [member1 copy]; member2.name = @"zhang"; member2.vipPhone = @"13200009999"; NSLog(@"member1:%d, member2:%d", [member1 retainCount], [member2 retainCount]); NSLog(@"member1:%@", member1); NSLog(@"member2:%@", member2);
member1:1, member2:1
member1:<VIPMember>{member:<Member>{name:wang},vipPhone:13422223333}
member2:<VIPMember>{member:<Member>{name:zhang},vipPhone:13200009999}