1. 设计拷贝的目的:让原对象生成一个副本。
拷贝分两种,一种是产生新的对象(深拷贝,具体见3),且新对象修改时不影响原对象;另外一种是如果原对象本身就是个不可变对象再调用copy的对象,为了性能着想,干脆返回自身。(浅拷贝(只有不可变对象调用copy方法才会发生浅拷贝))
2.两种实现拷贝的方式:
想调用copy方法,必须实现NSCopying协议,生成的是不可变的副本
想调用mutableCopy方法,实现NSMutableCopying,生成的是可变副本。
3. 深拷贝:内存里的对象直接拷贝一份(内容拷贝)。
浅拷贝:只是拷贝指针地址(地址拷贝)。相当于retain
4. 深拷贝和浅拷贝的区别:
深拷贝:拷贝内容,且产生新对象。新对象计数器置为1,原对象计数器不变。副本对象改变时不改变原对象
浅拷贝:拷贝地址,不产生新对象。原对象计数器加1.只有一种情况是浅拷贝(不可变对象调用不可变的copy方法)
5. 当成员变量是NSString的时候,setter策略一般用copy,其他情况一般用retain。
6. 实现NSCopying协议,即实现copyWithZone:方法,参数是副本对象的内存地址。为了防止子类初始化方法有问题,最好是用[self class]代替类名:
id copy = [[[self class] allocWithZone:zone] init];
例:
Student.h:
#import <Foundation/Foundation.h>
@interface Student : NSObject <NSCopying>
// NSString的成员变量setter策略最好用copy
@property (nonatomic, copy) NSString *name;
+ (id)studentWithName: (NSString *)name;
@end
Student.m:
#import "Student.h"
@implementation Student
+ (id)studentWithName:(NSString *)name {
Student *student = [[Student alloc] init];
student.name = name;
return student;
}
-(id)copyWithZone:(NSZone *)zone {
Student *copy = [[[self class] allocWithZone:zone] init];
copy.name = _name;
return copy;
}
- (NSString *)description {
return [NSString stringWithFormat:@"%p name = %@",self, _name];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [Student studentWithName:@"zzq"];
NSLog(@"%@", student);
// 从内存地址的不同可以看出来,副本是新的对象
Student *copy = [student copy];
NSLog(@"%@", copy);
}
return 0;
}