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, 0x7fff57519a48
strong string: 0x7fe441592e20, 0x7fe44159e1f8
copy 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, 0x7fff57519a48
strong string: 0x7fe441592e20, 0x7fe44159e1f8
copy string: 0x7fe441592e20, 0x7fe44159e200
origin string: abc333
strong string: abc333
copy string: abc
结论
1. 当源数据是NSString类型时,使用copy/strong/assign结果是一样的,都是对对象地址进行拷贝是浅拷贝
2. 当源数据是NSMutableString类型时,使用copy对象地址改变,是一个新对象,属于深拷贝。strong/assign地址相同,属于浅拷贝
3. 所以在修饰string时还是尽量使用copy,避免带来意想不到的问题。
最后推荐一个自己感觉总结非常好的简书:https://www.jianshu.com/p/2e1b3f54b4f3