类的copy和deepcopy

时间:2025-02-19 12:08:14

- (instancetype)initWithName:(NSString *)name

age:(NSUInteger)age

sex:(CYLSex)sex {

if(self = [super init]) {

_name = [name copy];

_age = age;

_sex = sex;

_friends = [[NSMutableSet alloc] init];

}

return self;

}

- (void)setName:(NSString *)name {

_name = [name copy];

}

- (id)copyWithZone:(NSZone *)zone {

CYLUser *copy = [[[self class] allocWithZone:zone]

initWithName:_name

age:_age

sex:_sex];

copy->_friends = [_friends mutableCopy];

return copy;

}

- (id)deepCopy {

CYLUser *copy = [[[self class] allocWithZone:zone]

initWithName:_name

age:_age

sex:_sex];

copy->_friends = [[NSMutableSet alloc] initWithSet:_friends

copyItems:YES];

return copy;

}