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.
Your three options have different semantics:
retain
/release
objects you store into myPrivateVar
.@interface
and the scope of many method (or function) definitions are "global" - effectively class variables (which Objective-C has no special syntax for). Such a variable is shared by all instances of MyClass
.retain
means that there is no need for retain
/release
when you do not have garbage collection.So don't use 2! Option 3 clearly has benefits if you don't have garbage collection, it provides some measure of abstraction over option 1, and is more costly - though you will probably not notice the difference outside of computationally intensive code which access the variable heavily.
Update 2015
Where garbage collection is used above ARC (automatic reference counting) is now more applicable (garbage collection is now deprecated). Also there is now a fourth option:
Declare them in the implementation section of the m file:
@implementation MyClass
{
NSObject * myPrivateVar;
}
Unlike option (2) this does declare an instance variable. The variable is private to the implementation, and with ARC memory management is automatic. The choice between this and (3) [which incidentally also no longer requires the @synthesize
] comes down to choice and need; properties give you dot syntax, the ability to customise the setter and/or getter, and the copy
attribute for automatic copy on assignment, but if you need none of these you can simply use the an instance variable.