NSString 属性:复制还是保留? [英] NSString property: copy or retain?

查看:27
本文介绍了NSString 属性:复制还是保留?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 SomeClass 的类,它有一个 string 属性名称:

@interface SomeClass : NSObject{NSString* 名称;}@property(非原子,保留)NSString* 名称;@结尾

我知道该名称可能会被分配一个 NSMutableString,在这种情况下,这可能会导致错误的行为.

  • 对于一般的字符串,使用 copy 属性而不是 retain 是否总是一个好主意?
  • 复制"属性是否比保留"属性效率低?

解决方案

对于类型为符合 NSCopying 协议的不可变值类的属性,您几乎总是应该指定 copy 在您的 @property 声明中.在这种情况下,您几乎从不想要指定 retain.

这就是您想要这样做的原因:

NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];Person *p = [[[Person alloc] init] autorelease];p.name = someName;[someName setString:@"Debajit"];

Person.name 属性的当前值将根据属性声明为 retain 还是 copy 而有所不同 — 它将是@"Debajit" 如果属性被标记为 retain,但是 @"Chris" 如果属性被标记为 copy.

因为在几乎所有情况下您都希望防止在背后改变对象的属性,所以您应该标记代表它们的属性copy.(如果您自己编写 setter 而不是使用 @synthesize,您应该记住在其中实际使用 copy 而不是 retain.)>

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 of retain?
  • 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 属性:复制还是保留?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆