目的:我们修改字符串的时候,是不想连带把属性也修改的
测试结果是:
用strong修饰的NSString会
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, copy) NSString *copyedString;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self demo2];
// 对于不可变字符串而言,使用strong和copy都是浅拷贝,打印的地址都是一致的
NSString *string = [NSString stringWithFormat:@"123"];
self.strongString = string;
self.copyedString = string;
NSLog(@" string: %p",string);
NSLog(@" strongString : %p",self.strongString);
NSLog(@" copyedString : %p",self.copyedString);
}
// 测试可变字符串使用copy属性(其实使用copy属性 相当于该变量进行了一次copy操作[string copy])
- (void)demo2{
// 不可变字符串
NSMutableString *string = [NSMutableString stringWithFormat:@"123"];
// 用strong修饰的属性记录
self.strongString = string;
// 用copy修饰的属性记录
self.copyedString = string;
// 打印地址
NSLog(@" string: %p",string);
NSLog(@" strongString : %p",self.strongString);
NSLog(@" copyedString : %p",self.copyedString);
NSLog(@"%@",self.copyedString);
// 改变字符串,对比用strong和copy修饰的属性的区别
[string appendString:@"bbb"];
NSLog(@" strongString : %@ %p",self.strongString, self.strongString);
NSLog(@" copyedString : %@ %p",self.copyedString, self.copyedString);
}
@end
小结:
demo2 打印结果:
我们发现用copy修饰的属性地址已经变了,原因是NSMutableString的对象copy操作 产生新地址,产生的是不可变的对象,所以改变string,,不会改变被copy修饰的属性.正好符合我们改变string 不会改变self.copyedstring的值,而self.strongstring的值已经改变了
2016-01-29 18:51:16.227 strongAndCopy[1804:166346] string: 0x7ae3a0c0
2016-01-29 18:51:16.227 strongAndCopy[1804:166346] strongString : 0x7ae3a0c0
2016-01-29 18:51:16.228 strongAndCopy[1804:166346] copyedString : 0x7ae39510
2016-01-29 18:51:16.228 strongAndCopy[1804:166346] 123
2016-01-29 18:51:16.228 strongAndCopy[1804:166346] strongString : 123bbb 0x7ae3a0c0
2016-01-29 18:51:16.228 strongAndCopy[1804:166346] copyedString : 123 0x7ae39510