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
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
is a subclass of NSString
, so it's entirely possible that someone might set your NSString*
property to point to a mutable string, thus creating the potential for the string to be changed while you're using it;NSString
, copy operations end up just retaining the original object anyway.Considering those three points, it's hard to think of a good reason to use retain
instead of copy
for your NSString
properties.
prefer copy
. it does not matter whether your class is or is not a singleton.
i wrote a fairly lengthy explanation for this, which details mutable and immutable types here: NSMutableString as retain/copy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With