Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I use retain or copy in my singleton?

Tags:

ios

iphone

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
like image 320
milof Avatar asked May 31 '11 05:05

milof


2 Answers

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:

  1. You usually don't want a string property to change under your nose;
  2. 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;
  3. For immutable classes like 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.

like image 71
Caleb Avatar answered Sep 29 '22 12:09

Caleb


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

like image 37
justin Avatar answered Sep 29 '22 11:09

justin