1、NSString為何要用copy。而不是strong/assign。
案例1:
@interface Test () @property (nonatomic, strong) NSString *strongString; @property (nonatomic, copy) NSString *copyedString;@end@implementation-(void)test{ 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);}@end
結果:
origin string: 0x7fe441592e20, 0x7fff57519a48strong string: 0x7fe441592e20, 0x7fe44159e1f8copy string: 0x7fe441592e20, 0x7fe44159e200
案例2:
@interface Test () @property (nonatomic, strong) NSString *strongString; @property (nonatomic, copy) NSString *copyedString;@end@implementation-(void)test{ NSMutableString *string = [NSMutableString 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); // 是否會有意想不到的事情發生呢 [string appendString:@"333"]; NSLog(@"origin string:%@", mStr); NSLog(@"strong string:%@", _rStr); NSLog(@"copy string:%@", _cStr);}@end
結果:
origin string: 0x7fe441592e20, 0x7fff57519a48strong string: 0x7fe441592e20, 0x7fe44159e1f8copy string: 0x7fe441592e20, 0x7fe44159e200origin string: abc333strong string: abc333copy string: abc
結論
1. 當來源資料是NSString類型時,使用copy/strong/assign結果是一樣的,都是對對象地址進行拷貝是淺拷貝
2. 當來源資料是NSMutableString類型時,使用copy對象地址改變,是一個新對象,屬於深拷貝。strong/assign地址相同,屬於淺拷貝
3. 所以在修飾string時還是盡量使用copy,避免帶來意想不到的問題。
最後推薦一個自己感覺總結非常好的簡書:https://www.jianshu.com/p/2e1b3f54b4f3