Example iVar foo
,
@property (nonatomic) NSString* foo; // inside .h
Option 1
@Synthesize foo; //Inside .m
foo = [[NSString alloc] init]; // viewDidLoad method
Option 2
@Synthesize foo; //Inside .m
self.foo = [[NSString alloc] init]; // viewDidLoad method
Option 3
@Synthesize foo = _foo; //Inside .m
_foo = [[NSString alloc] init]; // viewDidLoad method
At so many places I have seen code which has different ways of doing init an Object in Obj - C but which one is the best practise?
In this regard, ARC is the same as MRC.
you have specified all these take place in viewDidLoad
. in that case, use the setter (Option 2).
if you were to initialize/set in the initializer, then you would use direct access. the basic reason is that in the initializer (e.g. -init
), you have a partially initialized object. during initialization, you want to focus on initializing variables your class needs or expects in order to function correctly. as well, you want to avoid side-effects you can encounter when using the accessors in partially constructed states.
in a fully constructed state (e.g. viewDidLoad
), you should relegate the implementation to the accessors for correct behavior, as specified by your object's interface.
Additional Reading:
Initializing a property, dot notation
Should I refer to self.property in the init method with ARC?