سؤال

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

Why?

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?

Why would you use an ivar?

نصائح أخرى

I think you should understand the difference between these three and then decide which one is good for you.

option 1: Here while initializing you are not using the synthesizer method. so there is no use of declaring property-synthesizer in .h and .m

option 2: here you are using property-synthesizer. But the name of the method for accessing the instance and actual instance variable is same.

option 3: Here again you are not using the property-synthesizer method. Here foo is the name of the method and _foo is the actual instance.

In my opinion third one is the good. Since you the difference you can decide which one is good for you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top