我在单身人士中使用保留或复制吗?

mil*_*lof 8 iphone ios

我读到某个地方,在一个对象中使用NSString,必须使用copy而不是retain.有人可以解释这是否正确,为什么?

例如,我的单身人士有以下声明:

#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
Run Code Online (Sandbox Code Playgroud)

Cal*_*leb 8

我认为"必须" 必须有点强烈.您可以使用copyretain,但通常应该copy用于您的NSString*属性,因为:

  1. 你通常不希望在你的鼻子下改变一个字符串属性;
  2. NSMutableString是一个子类NSString,所以完全有可能有人可能将你的NSString*属性设置为指向一个可变字符串,从而创建了在你使用它时改变字符串的可能性;
  3. 对于不可变的类NSString,复制操作最终只是保留原始对象.

考虑到这三点,很难想出一个很好的理由来retain代替copy你的NSString财产.