使用copy跟strong修饰属性的异同
首先声明2个属性,分别是strong,copy修饰
@property (nonatomic,strong) NSString *stringStrong;
@property (nonatomic,copy) NSString *stringCopy;
分别给它们赋值,查看结果
NSString *strong1 = @"i am strong1";
NSString*copy1 =@"i am copy";
NSMutableString *mutStrong2 = [NSMutableString stringWithString:@"i am mtuStrong"];
NSMutableString *mutCopy2 = [NSMutableString stringWithString:@"I am mtuCopy"];
self.stringStrong= strong1;
self.stringCopy= copy1;
NSLog(@"strong1 = %p\n self.stringStrong = %p\n copy1 = %p\n self.strngCopy = %p",strong1,self.stringStrong,copy1,self.stringCopy);
/*ThroughTenInterview[64049:924857] strong1 = 0x106035078
self.stringStrong = 0x106035078
copy1 = 0x106035098
self.strngCopy = 0x106035098 输出结果表示使用copy跟strong修饰过的属性都是浅复制*/
NSLog(@"mutStrong2 = %p\n self.stringStrong = %p\n mutCopy2 = %p\n self.strngCopy = %p",mutStrong2,self.stringStrong,mutCopy2,self.stringCopy);
/*mutStrong2 = 0x60c00044b730
self.stringStrong = 0x60c00044b730
mutCopy2 = 0x60c00044b460
self.strngCopy = 0x600000034300
输出结果表明,mutCopy2是通过深复制后才赋值给self.stringCopy*/
结论
copy跟strong的共同点是 ,它们都对对象进行了浅拷贝,对不可变类型它们的作用是相同的。给对象赋值后对象引用计数加1。不同点是,strong对于可变对象也是浅拷贝,而copy对可变对象是深拷贝。所以这是为啥建议大家在修饰不可变对象的时候使用的是copy来修饰属性。因为copy对可变类型是深拷贝,所以如果给一个不可变对象赋值一个可变类型时,当可变类型改变后,copy修饰的属性不会改变。但是使用strong修饰的对象会改变。
copy跟mutableCopy的区别
下面分别声明一个不可变字符串,一个可变字符串
NSString *str = @"I am str";
NSMutableString *mutStr = [NSMutableString stringWithString:@"I am mutStr"];
NSString* strCopy = [strcopy];
NSString*mutStrCopy = [mutCopy2copy];
NSString*strMutCopy = [strmutableCopy];
NSString*mutStrMutCopy = [mutStrmutableCopy];
NSLog(@"str = %p\n strCopy = %p\n mutStr = %p\n mutStrCopy = %p\n strMutCopy = %p\n,mutStrMutCopy = %p",str,strCopy,mutStr,mutStrCopy,strMutCopy,mutStrMutCopy);
/*ThroughTenInterview[65940:961670] str = 0x1071731b8
strCopy = 0x1071731b8
mutStr = 0x60000044e580
mutStrCopy = 0x60000044d770 输出结果说明 copy对不可变对象是浅拷贝,对可变类型是深拷贝,mutStrMutCopyd都是深拷贝*/
结论
copy对不可变对象是浅拷贝,对可变对象是深拷贝。mutableCopy的对像都是深拷贝。
深拷贝跟浅拷贝
深拷贝:对象拷贝,会产生新的对象,源对象的引用计数器不变;
浅拷贝:指针拷贝,不产生新的对象,源对象的引用计数器+1;