目的:咱们修改字符串的时候,是不想连带把属性也修改的app
测试结果是:测试
用strong修饰的NSString会atom
#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
小结:code
demo2 打印结果:orm
咱们发现用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 : 0x7ae3a0c0string
2016-01-29 18:51:16.228 strongAndCopy[1804:166346] copyedString : 0x7ae39510it
2016-01-29 18:51:16.228 strongAndCopy[1804:166346] 123io
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