** 差异化分析如下:**
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, copy) NSString *copyedString;
- (void)testCopyAndStrong {
NSString *string = [NSString stringWithFormat:@"abc"];
self.strongString = string;
self.copyedString = string;
NSLog(@"origin string: %p, %p", string, &string);
NSLog(@"没变strong string: %p, %p", _strongString, &_strongString);
NSLog(@"copy string: %p, %p", _copyedString, &_copyedString);
NSLog(@"你发现上面的地址是一样的;看下面--");
NSMutableString * strMutable = [[NSMutableString alloc] initWithString:@"123"];
self.strongString = strMutable;
self.copyedString = strMutable;
NSLog(@"origin string: %p, %p", strMutable, &strMutable);
NSLog(@"没变strong string: %p, %p", _strongString, &_strongString);
NSLog(@"这个深拷贝啦,地址变啦copy string: %p, %p", _copyedString, &_copyedString);
NSLog(@"总结下就是copy 属性对nsstring 类型的赋值操作没有影响,只会对mutableString 有影响,前者和strong没有区别,都是进行retain +1 操作,后者除此之外还进行了深拷贝,前者只是引用");
[strMutable appendString:@"appendString"];
NSLog(@"origin string: %@", strMutable);
NSLog(@"和赋值源值保持一致:strong string: %@", _strongString);
NSLog(@"值不在变化copy string: %@", _copyedString);
}
运行结果:
2017-05-17 16:54:22.977 origin string: 0xa000000006362613, 0x7fff5793b708 2017-05-17 16:54:22.977 没变strong string: 0xa000000006362613, 0x7f9bc370a5b0 2017-05-17 16:54:22.977 copy string: 0xa000000006362613, 0x7f9bc370a5b8 2017-05-17 16:54:22.977 你发现上面的地址是一样的;看下面-- 2017-05-17 16:54:22.978 origin string: 0x6080002603c0, 0x7fff5793b700 2017-05-17 16:54:22.978 没变strong string: 0x6080002603c0, 0x7f9bc370a5b0 2017-05-17 16:54:22.978 这个深拷贝啦,地址变啦copy string: 0xa000000003332313, 0x7f9bc370a5b8 2017-05-17 16:54:22.978 总结下就是copy 属性对nsstring 类型的赋值操作没有影响,只会对mutableString 有影响,前者和strong没有区别,都是进行retain +1 操作,后者除此之外还进行了深拷贝,前者只是引用 2017-05-17 16:54:22.978 origin string: 123appendString 2017-05-17 16:54:22.979 和赋值源值保持一致:strong string: 123appendString 2017-05-17 16:54:22.979 值不在变化copy string: 123
关于block 需要注意的copy 属性
- 通常自定义block 属性采用copy 修饰:
默认情况下,block是存档在栈中,可能被随时回收,通过copy操作可以使其在堆中保留一份, 相当于一直强引用着, 因此如果block中用到self时, 需要将其弱化, 通过__weak或者__unsafe_unretained; 如使用assgin 修饰可能出现当前block 所在代码段执行完毕后,区域中的局部变量等会被系统回收释放,再次访问block 时出现野指针的现象
@interface ViewController ()
@property (nonatomic, copy) void(^myblock)();
@end
总结copy使用场景如下 :用于存在可变类的非可变引用对象以及(块)Block
@property (nonatomic, copy)NSString * testStr;
@property (nonatomic, copy)NSArray * testArray;
@property (nonatomic, copy)NSDictionary * testDic;
@property (nonatomic, copy)Block block;//块