首先问一个问题,为什么NSString要用copy修饰,用strong修饰不行么?
先模拟一个错误的场景,一个person类,有一个用strong修饰的属性叫 s_name,并且之前的复制变量还想重复使用到其他场景,我们创建一个ViewController的对象VC并持有person类对象person;并执行下边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);
}
输出结果:
'2016-08-1205:51:21.262TestCopy[64714:20449045]iOS
2016-08-1205:51:21.262TestCopy[64714:20449045]iOS Swift'
发现我们仅仅对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);
}
输出结果:
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);
}
输出结果:
2016-08-12 06:03:40.226 TestCopy[64922:20479646] iOS
2016-08-12 06:03:40.227 TestCopy[64922:20479646] iOS
现在知道为什么要用copy了吧,也就是在一个特定场景下:我们通过一个NSMutableString对String变量进行复制,如果string的property为strong修饰时,就会随着NSMutableString类型的变量一起变化!!