// 首先定义2个属性 @property (nonatomic, strong) NSString *stStr; @property (nonatomic, copy) NSString *coStr; // 测试 - (void)_strong_copy { NSMutableString *mutableStr = [NSMutableString stringWithFormat:@"abc"]; self.stStr = mutableStr; self.coStr = mutableStr; NSLog(@"mutableStr:%p, %p", mutableStr, &mutableStr); NSLog(@"strongStr :%p, %p", _stStr, &_stStr); NSLog(@"copyStr :%p,%p", _coStr, &_coStr); NSLog(@" "); [mutableStr appendString:@"de"]; NSLog(@"mutableStr:%p", mutableStr); NSLog(@"retainStr :%@", _stStr); NSLog(@"copyStr :%@", _coStr); }
控制器Log:
2016-07-04 15:59:20.117 Demo_OC[20588:1058116] mutableStr:0x7fece3c13860, 0x7fff56bf8cd8 2016-07-04 15:59:20.117 Demo_OC[20588:1058116] strongStr :0x7fece3c13860, 0x7fece3e8d428 2016-07-04 15:59:20.118 Demo_OC[20588:1058116] copyStr :0xa000000006362613,0x7fece3e8d430 2016-07-04 15:59:20.118 Demo_OC[20588:1058116] mutableStr:0x7fece3c13860 2016-07-04 15:59:20.118 Demo_OC[20588:1058116] retainStr :abcde 2016-07-04 15:59:20.118 Demo_OC[20588:1058116] copyStr :abc
通过日志我们可以分析:
1、mutableStr 被修改时,strong修饰的字符串值发生了变化;copy修饰的字符串值未发生变化。
结论:strong修饰的字符串仅仅是浅拷贝,本身会随着mutableStr改变而改变;而copy修改的字符串是深拷贝,不会随着mutableStr改变而改变。
2、使用copy修饰的字符串更安全一些,可以保证我们的值不会随着mutableStr的改变而改变。