-
copy 常用在修饰NSString * 和block类型的属性
比如:
@property (nonatomic, copy) NSString *name;
因为:大部分声明一个属性都是用copy修饰字符串,因为系统实现set方法中,拷贝了一份这个属性的赋值,所以以后外界再次修改了这个属性的值,不会影响原来的值. -
copy语法的作用:
- 1.产生一个副本(如果是不可变字符串,调用这个方法不产生新的对象,只是地址拷贝,如果是可变字符串调用这个方法,则一定会产生一个新的副本对象,地址不一样,可以进行打印验证)
- 2.修改了副本,并不会影响源对象;
-
NSMutableCopy 继承于NSCopy
-
调用了mutableCopy:方法一定会产生一个新的副本对象
@property (nonatomic, copy) NSString *name;
没有@property (nonatomic,mutableCopy) NSString *name;
在系统自动生成的set方法中,赋值的时候调用了copy方法
用copy修饰字符串的好处:当把字符串赋值给成员变量后,以后再次修改外面的字符串,都不会影响里面属性的值;
-(void)setName:(NSString *)name
{
_name = [name copy];
}
所以字符串不一定用copy,看需求,如果我们想要这个属性的值随外面的字符串发生改变,那么我们就应该用strong代替copy;
简单介绍自定义类的copy
-
首先自定义的类不存在mutableCopy,自定义的类没有可变的,只有字符串和数组和字典有才有mutableCopy,他们是系统定义好的,并且在系统内部声明中已经遵守了
<NSCopying,NSMutableCopying>
-
普通自定义对象如何拷贝?
- 1.遵守协议
<NSCopying>
- 2.实现下面的方法
- 1.遵守协议
// zone:系统分配好的内存空间,用于存放生成的新的对象;
-(id)coypWithZone:(NSZone *)zone
{
DXCar *copyCar = [DXCar allocWithZone:zone] init];
//给属性赋值:
copyCar.price = self.price;
return copyCar;
}