若想令自己的类具有拷贝功能,则需实现NSCopying 协议,如果自定义的对象分为可变版本与不可变版本的话,那就要同时实现NSCopying与NSMutableCopying协议
具体步骤
1 声明该类遵从NSCopying协议
2.实现NSCopying 这个协议只有一个方法
-(id)copyWithZone:(NSZone*)zone;
- (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(CYLSex)sex;
这么实现的
- (id)copyWithZone:(NSZone *)zone {
CYLUser *copy = [[[self class] allocWithZone:zone]
initWithName:_name
age:_age
sex:_sex];
return copy;
}
- (void)setName:(NSString *)name {
if (_name != name) {
//[_name release];//MRC
_name = [name copy];
}
}
那如何确保 name 被 copy?在初始化方法(initializer)中做:
- (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;
}
网友评论