I would like to know what the recommendations are for declaring private instance variables in cocoa. This question is in the context of developing apps on the iPhone.
I am aware of at least three ways of declaring private variables:
Declare them in the interface of the h file with the modifier @private:
@interface MyClass : NSObject {
@private
NSObject * myPrivateVar;
}
Declare them in the implementation section of the m file:
@implementation MyClass
NSObject * myPrivateVar;
Declare a property in the interface of the m file (not even declaring the variable itself):
@interface MyClass ()
@property (nonatomic, retain) NSString* myPrivateVar;
@end
@implementation
@synthesize myPrivateVar;
So far, I have used extensively 2 but recently came to realize this might be dangerous due to the lack of garbage collection. Are there cases where it remains perfectly acceptable to use that method?
Is 3 more appropriate? Does the answer depend on the object type (e.g. mutable/immutable)?
Pointers to reference material discussing the trade offs for using/not using properties in general also appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…