string修饰的梦修改吗_知识点!!!NSString用copy和strong修饰的区别
廢話不多說直接上例子。結果在下邊!!!!!
用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
如果你對性能要求特別高,或者是個代碼極客。。那么能用strong就不用copy,畢竟copy修飾時,set方法中會多出對copy的相關操作。
切記!!!!!!!!!!!!!!
復制一定要用self,因為self相當于[self setStr1:str2] 會調用set方法,set方法里面有玄機。如果用_str 是得不到這個結果的。
總結
以上是生活随笔為你收集整理的string修饰的梦修改吗_知识点!!!NSString用copy和strong修饰的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 两栈共享空间
- 下一篇: 去掉数组最后一个元素_leetcode