在ARC存在的情况下init iVar变量的正确方法是什么 [英] What is the correct way of init iVar variables in presence of ARC
问题描述
示例iVar foo
,
@property (nonatomic) NSString* foo; // inside .h
选项1
@Synthesize foo; //Inside .m
foo = [[NSString alloc] init]; // viewDidLoad method
选项2
@Synthesize foo; //Inside .m
self.foo = [[NSString alloc] init]; // viewDidLoad method
选项3
@Synthesize foo = _foo; //Inside .m
_foo = [[NSString alloc] init]; // viewDidLoad method
为什么?
在很多地方,我看过代码有不同的方法在Obj - C中初始化一个对象,但哪一个是最好的做法?
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?
推荐答案
在这方面,ARC与MRC相同。
In this regard, ARC is the same as MRC.
您已指定所有这些发生在 viewDidLoad
。在这种情况下,使用setter(选项2)。
you have specified all these take place in viewDidLoad
. in that case, use the setter (Option 2).
如果要在初始化程序中初始化/设置,那么您将使用直接访问。基本原因是在初始值设定项(例如 -init
)中,您有一个部分初始化的对象。在初始化期间,您希望专注于初始化类所需或期望的变量,以便正常运行。此外,您还想避免在遇到副作用时遇到在完全构造的状态下使用部分构造状态的访问器。
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.
(例如 viewDidLoad
),你应该放弃根据对象的界面指定对访问者实现正确行为。
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.
补充阅读:
我应该在使用ARC的init方法中引用self.property吗?
这篇关于在ARC存在的情况下init iVar变量的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!