我在单身人士中使用保留或复制吗? [英] Do I use retain or copy in my singleton?
本文介绍了我在单身人士中使用保留或复制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我读到某个地方,在对象中使用NSString,必须使用copy而不是retain。有人可以解释这是否正确以及为什么?
I read somewhere that with NSString in an object, one has to use copy instead of retain. Can someone explain if this is correct and why?
例如我对我的单身人士有以下声明:
For example I have the following declaration for my singleton:
#import <foundation/Foundation.h>
@class FaxRecipient;
@interface MyManager : NSObject {
NSString *subject;
NSString *reference;
NSString *coverSheet;
FaxRecipient *faxRecipient;
}
@property (nonatomic, retain) NSString *test1;
@property (nonatomic, retain) NSString *test2;
@property (nonatomic, retain) NSString *test3;
@property (nonatomic,retain) FaxRecipient *faxRecipient;
+ (id)sharedManager;
@end
推荐答案
我认为必须在必须的意义上是有点强大的。您可以使用复制
或保留
,但应 >通常使用复制
为您的 NSString *
属性,因为:
I think "has to" in the sense of must is a little strong. You can use either copy
or retain
, but you should generally use copy
for your NSString*
properties because:
- 你通常不希望在你的鼻子下改变一个字符串属性;
-
NSMutableString
是NSString
的子类,所以有人可能会将NSString *
属性设置为指向可变字符串,因此在你使用它时创建了更改字符串的可能性; - 对于像
NSString
这样的不可变类,复制操作结束无论如何,只保留原始对象。
- You usually don't want a string property to change under your nose;
NSMutableString
is a subclass ofNSString
, so it's entirely possible that someone might set yourNSString*
property to point to a mutable string, thus creating the potential for the string to be changed while you're using it;- For immutable classes like
NSString
, copy operations end up just retaining the original object anyway.
考虑到这三点,很难想出使用<$ c $的充分理由c>为您的 NSString
属性保留而不是 copy
。
Considering those three points, it's hard to think of a good reason to use retain
instead of copy
for your NSString
properties.
这篇关于我在单身人士中使用保留或复制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文