废话不多说直接上例子。结果在下边!!!!!
用strong修饰:
@interface ViewController ()
@property(nonatomic,strong)NSString *str1;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableString *str2 =[NSMutableString stringWithString:@"111"];
self.str1 = str2;
NSLog(@"str1:%@",self.str1);
[str2 appendString:@"22"];
NSLog(@"str1:%@",self.str1);
}
打印结果:
2017-08-28 11:15:10.273 20170828demo[2789:529874] str1:111
2017-08-28 11:15:10.273 20170828demo[2789:529874] str1:11122
用copy修饰:
@interface ViewController ()
@property(nonatomic,copy)NSString *str1;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableString *str2 =[NSMutableString stringWithString:@"111"];
self.str1 = str2;
NSLog(@"str1:%@",self.str1);
[str2 appendString:@"22"];
NSLog(@"str1:%@",self.str1);
}
打印结果:
2017-08-28 11:16:17.009 20170828demo[2823:536589] str1:111
2017-08-28 11:16:17.009 20170828demo[2823:536589] str1:111
如果用可变字符串给str1赋值,用copy会对str1做深拷贝,这样str2改变str1不变。用strong只是引用计数加一,并不做深拷贝。所以为了保障str1的值不被改变用copy修饰。当然如果你确定str1未来接受的字符串是不可变类型,用strong也无妨。
像这样:
@interface ViewController ()
@property(nonatomic,strong)NSString *str1;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *str2 =@"111";
self.str1 = str2;
NSLog(@"str1:%@",self.str1);
str2 = @"222";
NSLog(@"str1:%@",self.str1);
}
打印结果:
2017-08-28 11:28:56.649 20170828demo[2948:602140] str1:111
2017-08-28 11:28:59.107 20170828demo[2948:602140] str1:111