22: 理解NSCopying协议

1.NSCopying协议

若想令自定义对象具有拷贝功能,则需要实现NSCopying协议

  • 实现copyWithZone方法
    方法中应该用全能初始化方法,来初始化待拷贝的对象

//.h
@interface Person : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,readonly) NSArray *friends;
@property (nonatomic,assign) int age;
- (instancetype)initWithName:(NSString *)name age:(int)age;
@end
//.m
@interface Person ()
@property (nonatomic,readwrite,strong) NSMutableArray *friends;
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name age:(int)age
{
self = [super init];
if (self) {
self.name = name;
self.age = age;
_friends = [NSMutableArray array];
}
return self;
}
...
- (id)copyWithZone:(NSZone *)zone{
Person *p = [[[self class] allocWithZone:zone] initWithName:_name age:_age];
return p;
}
@end

  • 如果全能初始化不能满足要求,还应该手动的加上一些操作

 //.h
@interface Person : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,readonly) NSArray *friends
@property (nonatomic,assign) int age;
- (instancetype)initWithName:(NSString *)name age:(int)age;
@end
//.m
@interface Person ()
@property (nonatomic,readwrite,strong) NSMutableArray *friends;
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name age:(int)age
{
self = [super init];
if (self) {
self.name = name;
self.age = age;
_friends = [NSMutableArray array];
}
return self;
}
...
- (id)copyWithZone:(NSZone *)zone{
Person *p = [[[self class] allocWithZone:zone] initWithName:_name age:_age];
p->_friends = [_friends mutableCopy]; //额外的代码

return p;
}
@end

  • 如果自定义对象分为可变版本和不可变版本,那么就要同时实现NSCopying与NSMutableCopying协议

  • 深拷贝浅拷贝的对比图

22: 理解NSCopying协议_第1张图片
Paste_Image.png
  • 复制对象时应该决定是深拷贝还是浅拷贝,一般情况下是浅拷贝,如果你所写的对象需要深拷贝,那么需要新增一个专门执行深拷贝的方法

你可能感兴趣的:(22: 理解NSCopying协议)