首先問一個問題,為什么NSString要用copy修飾,用strong修飾不行么?
先模擬一個錯誤的場景,一個person類,有一個用strong修飾的屬性叫 s_name,并且之前的復制變量還想重復使用到其他場景,我們創(chuàng)建一個ViewController的對象VC并持有person類對象person;并執(zhí)行下邊test1方法.
-(void)test1{
self.person = [[Person alloc]init];
NSMutableString *name = [NSMutableString stringWithFormat:@"IOS"];
self.person.s_name = name;
NSLog(@"%@",self.person.s_name);
[name appendingString:@" Swift"];
NSlog(@"%@",self.person.s_name);
}
輸出結(jié)果:
'2016-08-1205:51:21.262TestCopy[64714:20449045]iOS
2016-08-1205:51:21.262TestCopy[64714:20449045]iOS Swift'
發(fā)現(xiàn)我們僅僅對name做了修改,為什么s_name也會改變,好下邊我們對代碼稍作修改
-(void)test2{
self.person = [[Person alloc]init];
NSMutableString *name = [NSMutableString stringWithFormat:@"IOS"];
self.person.s_name = name;
NSLog(@"%@",self.person.s_name);
name = @"IOS Swift";
NSlog(@"%@",self.person.s_name);
}
輸出結(jié)果:
2016-08-1205:56:57.162TestCopy[64842:20459179]iOS
2016-08-1205:56:57.162TestCopy[64842:20459179]iOS
在做一個實驗,我么用一個copy修飾的c_name 代替s_name
-(void)test3{
self.one=[[Personalloc]init];
NSMutableString*name=[NSMutableStringstringWithFormat:@"iOS"];
self.one.c_name=name;
NSLog(@"%@",self.one.c_name);
[nameappendString:@" Source Probe"];
NSLog(@"%@",self.one.c_name);
}
輸出結(jié)果:
2016-08-12?06:03:40.226?TestCopy[64922:20479646]?iOS
2016-08-12?06:03:40.227?TestCopy[64922:20479646]?iOS
現(xiàn)在知道為什么要用copy了吧,也就是在一個特定場景下:我們通過一個NSMutableString對String變量進行復制,如果string的property為strong修飾時,就會隨著NSMutableString類型的變量一起變化!!