1.NSCopying協(xié)議
若想令自己所寫的對(duì)象具有拷貝功能泣侮,則需要實(shí)現(xiàn)NSCopying協(xié)議
- 實(shí)現(xiàn)copyWithZone方法
- 方法中應(yīng)該用全能初始化方法,來(lái)初始化待拷貝的對(duì)象
//.h
@interface Person : NSObject <NSCopying>
@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
- 如果全能初始化不能滿足要求,還應(yīng)該手動(dòng)的加上一些操作
//.h
@interface Person : NSObject <NSCopying>
@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
- 如果自定義對(duì)象分為可變版本和不可變版本,那么就要同時(shí)實(shí)現(xiàn)NSCopying與NSMutableCopying協(xié)議
2.深拷貝與淺拷貝
-
深拷貝淺拷貝的對(duì)比圖
深拷貝與淺拷貝 - 復(fù)制對(duì)象時(shí)應(yīng)該決定是深拷貝還是淺拷貝,一般情況下是淺拷貝,如果你所寫的對(duì)象需要深拷貝,那么需要新增一個(gè)專門執(zhí)行深拷貝的方法