NSString属性:copy或retain? [英] NSString property: copy or retain?
问题描述
假设我有一个类 SomeClass
和 string
属性名称:
@interface SomeClass:NSObject
{
NSString * name;
}
@property(nonatomic,retain)NSString * name;
@end
我知道名称可能会分配一个 NSMutableString
在这种情况下,这可能会导致错误的行为。
- 对于一般的字符串,总是是一个好主意,使用
retain
? - 是否是复制的属性的效率低于这种保留属性?
@property
声明中的code> copy 。指定 retain
是在这种情况下几乎不想要的东西。 这里是为什么要这样做: / p>
NSMutableString * someName = [NSMutableString stringWithString:@Chris];
Person * p = [[[Person alloc] init] autorelease];
p.name = someName;
[someName setString:@Debajit];
Person.name
属性将根据属性是否声明 retain
或 copy
而不同 - 将会是 @Debajit
如果属性标记为 retain
,但 @Chris
if该属性标记为 copy
。
由于几乎在所有情况下您都希望突变背后的对象属性,您应该标记表示它们的属性 copy
。 (如果你自己编写安装器而不是使用 @synthesize
,你应该记住使用 copy
而不是保留
。)
Let's say I have a class called SomeClass
with a string
property name:
@interface SomeClass : NSObject
{
NSString* name;
}
@property (nonatomic, retain) NSString* name;
@end
I understand that name may be assigned a NSMutableString
in which case this may lead to errant behavior.
- For strings in general, is it always a good idea to use the
copy
attribute instead ofretain
? - Is a "copied" property in any way less efficient than such a "retain-ed" property?
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 *p = [[[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.)
这篇关于NSString属性:copy或retain?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!