What is the correct way of init iVar variables in presence of ARC

后端 未结 2 1518
北荒
北荒 2021-01-03 16:31

Example iVar foo,

@property (nonatomic) NSString* foo; // inside .h

Option 1

@Synthesize foo;         


        
相关标签:
2条回答
  • 2021-01-03 17:11

    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.

    0 讨论(0)
  • 2021-01-03 17:24

    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?

    0 讨论(0)
提交回复
热议问题