`
wsqwsq000
  • 浏览: 676544 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

NSString property中应该使用copy

 
阅读更多

 

 

For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration. Specifying retain is something you almost never want in such a situation.

Here's why you want to do that:

NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];

Person *= [[[Person alloc] init] autorelease];
p
.name = someName;

[someName setString:@"Debajit"];

The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but@"Chris" if the property is marked copy.

Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using@synthesize you should remember to actually use copy instead of retain in it.)

由此,我们也可以看出copy和retain的区别了。

 

 

分享到:
评论
2 楼 wsqwsq000 2012-06-04  
首先,你得了解retain和copy的区别。用retain的property进行赋值时,并不是string赋值,而是指向原有对象的内存,引用数加1而已。
Person *p = [[[Person alloc] init] autorelease];
p.name = someName;
我们本意是想将p.name = @"Chris";但是retain并不是string赋值,是将p.name指向someName内存块,这时候再进行[someName setString:@"Debajit"];,那么p.name就为@"Debajit",并不是我们所想要的结果。
1 楼 hhb19900618 2012-06-03  
你好 我还是不太明白为啥string要用copy

相关推荐

Global site tag (gtag.js) - Google Analytics