字符串什么时候用copy,什么时候用mutable copy

代码解释:

声明两个变量

@property (retain,nonatomic) NSString *rStr;

@property (copy, nonatomic)  NSString *cStr;

在viewDidLoad中添加如下代码:

NSMutableString *mStr = [NSMutableString stringWithFormat:@"abc"];

self.rStr  = mStr;

self.cStr    = mStr;

NSLog(@"mStr:%p,%p",  mStr,&mStr);

NSLog(@"retainStr:%p,%p", _rStr, &_rStr);

NSLog(@"copyStr:%p,%p",  _cStr, &_cStr);

[mStr appendString:@"de"];

NSLog(@"retainStr:%@",  _rStr);

NSLog(@"copyStr:%@",    _cStr);

NSString *mStr1 = [NSString stringWithFormat:@"abc"];

self.rStr  = mStr1;

self.cStr    = mStr1;

NSLog(@"mStr:%p,%p",  mStr1,&mStr1);

NSLog(@"retainStr:%p,%p", _rStr, &_rStr);

NSLog(@"copyStr:%p,%p",  _cStr, &_cStr);

[mStr1 stringByAppendingString:@"de"];

NSLog(@"retainStr:%@",  _rStr);

NSLog(@"copyStr:%@",    _cStr);

NSLog(@"mStr:%p,%p",  mStr1,&mStr1);

NSLog(@"retainStr:%p,%p", _rStr, &_rStr);

NSLog(@"copyStr:%p,%p",  _cStr, &_cStr);

输出结果:

mStr:0x7f935ac05980,0x7fff533609f8

retainStr:0x7f935ac05980,0x7f935aeb6390

copyStr:0xa000000006362613,0x7f935aeb6398

 retainStr:abcde

copyStr:abc


mStr:0xa000000006362613,0x7fff533609f0

retainStr:0xa000000006362613,0x7f935aeb6390

copyStr:0xa000000006362613,0x7f935aeb6398

retainStr:abc

copyStr:abc

mStr:0xa000000006362613,0x7fff533609f0

 retainStr:0xa000000006362613,0x7f935aeb6390

copyStr:0xa000000006362613,0x7f935aeb6398

总结: 把一个对象赋值给一个属性变量,当这个对象变化了,如果希望属性变量变化就使用strong属性,如果希望属性变量不跟着变化,就是用copy属性。当把NSMutableString赋值给NSString的时候,才会有不同,如果是赋值是NSString对象,那么使用copy还是strong,结果都是一样的,因为NSString对象根本就不能改变自身的值,它是不可变的.

你可能感兴趣的:(字符串什么时候用copy,什么时候用mutable copy)