目的:咱們修改字符串的時候,是不想連帶把屬性也修改的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