NSString使用strong仍是copy

🌰:atom

@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,也就是兩次賦值都增長了其引用計數spa

可是當string爲可變字符串時code

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

這個時候就有區別了,能夠看出,聲明爲strong時,賦值是賦的內存地址,而聲明爲copy的時候,實際上是對可變字符串進行了一次深拷貝,這時候string的引用計數爲2,cpString的引用計數爲1orm

相關文章
相關標籤/搜索