NSString使用strong还是copy

🌰:

@interface ViewController ()<NSCopying>

@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, copy) NSString *cpString;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *string = [NSString stringWithFormat:@"abc"];
    self.strongString = string;
    self.cpString = string;
    NSLog(@"string: %p, %p", string, &string);
    NSLog(@"strongString: %p, %p", _strongString, &_strongString);
    NSLog(@"cpString: %p, %p", _cpString, &_cpString);
}
string: 0xa000000006362613, 0x7ffee89deb88 
strongString: 0xa000000006362613, 0x7fc8e850cb00
cpString: 0xa000000006362613, 0x7fc8e850cb08

这个时候,是没有区别的,而且此时string的引用计数是3,也就是两次赋值都增加了其引用计数

但是当string为可变字符串时

string: 0x60400025fef0, 0x7ffee6b1fb88
strongString: 0x60400025fef0, 0x7fc57351f140
cpString: 0xa000000006362613, 0x7fc57351f148

这个时候就有区别了,可以看出,声明为strong时,赋值是赋的内存地址,而声明为copy的时候,其实是对可变字符串进行了一次深拷贝,这时候string的引用计数为2,cpString的引用计数为1

posted on 2018-01-29 23:29  咿呀呀呀呀咿  阅读(93)  评论(0编辑  收藏  举报

导航