美文网首页
OC中字符串为什么要用Copy

OC中字符串为什么要用Copy

作者: 请叫我攻城狮 | 来源:发表于2016-02-23 20:08 被阅读1170次

在iOS开发中,我们在定义一个NSString的时候都会用copy来修饰,

@property (nonatomic, copy)NSString *str;

那为什么不用strong呢,我写了一个测试,来简单的说明一下

首先把修饰符写成strong 

在viewDidLoad的方法中,定义一个可变的字符串

@property (nonatomic, strong)NSString *str;

- (void)viewDidLoad {

[super viewDidLoad];

NSMutableString *string = [NSMutableString string];

[string appendString:@"hello"];

self.str = string;

NSLog(@"%@",self.str);

[string appendString:@"World"];

NSLog(@"%@",self.str);

}

输出的结果是

NSString中copy的问题[3807:239891] hello

NSString中copy的问题[3807:239891] helloWorld

我们只给self.str附了一次值,但是self.str 的值改变了,这是因为把可变字符的地址指向了str,所以string的值改变了,self.str也跟着改变,

我们把strong改成copy以后

@property (nonatomic, copy)NSString *str;

输出的结果

 NSString中copy的问题[3852:242597] hello

 NSString中copy的问题[3852:242597] hello

输出的结果显示,self.str的值只做了一次的修改,

这样就能保证了在代码中,数据的安全

相关文章

网友评论

      本文标题:OC中字符串为什么要用Copy

      本文链接:https://www.haomeiwen.com/subject/diabkttx.html