如果我在-init中什么也不做,是否与仅调用[MyClass alloc]一样? [英] If I do nothing in -init, is it the same as just calling [MyClass alloc]?
问题描述
如果我有一个NSObject
子类,该子类要么没有-init
方法,要么根本没有在-init
中执行任何操作,那么通过以下两种方式创建的实例之间是否有任何区别:
If I have an NSObject
subclass which either has no -init
method or simply does nothing in -init
, is there any difference between an instance created these two ways:
MyClass *instance = [MyClass alloc];
MyClass *instance = [[MyClass alloc] init];
我的意思是在-init
中什么也不做"
By "does nothing in -init
" I mean
- (id)init {
self = [super init];
if (self) {
}
return self;
}
由于NSObject
的-init
方法本身不执行任何操作,因此我看不到有什么区别,但是当然建议您必须调用-init
进行正确的准备一个对象.
Since NSObject
's -init
method itself does nothing, I can't see there being any difference, but of course the advice is that you must call -init
to properly prepare an object.
Here's the snippet from NSObject
's -init
method which got me wondering about this:
NSObject类中定义的init方法不进行初始化;它只是返回自我.
The init method defined in the NSObject class does no initialization; it simply returns self.
推荐答案
如果我有一个
NSObject
子类,该子类要么没有-init
方法,要么 在-init
中什么都不做, 实例创建了以下两种方式:
If I have an
NSObject
subclass which either has no-init
method or simply does nothing in-init
, is there any difference between an instance created these two ways:
MyClass *instance = [MyClass alloc];
MyClass *instance = [[MyClass alloc] init];
技术上,没有区别.
但这并不意味着您出于各种原因应该使用裸露的+alloc
来创建实例,.
But that doesn't mean you should use a bare +alloc
to ever create an instance for a variety of reasons.
首先,它是事物的主体. Objective-C编码标准说,在 +alloc
之后应始终跟随-init
.
First, it is the principal of the thing. Objective-C coding standards say +alloc
should always be followed by -init
.
第二,这全都与一致性和代码维护有关.当您将MyClass
重构为某个类的子类,其中指定的初始化程序实际上很重要时,会发生什么?发生的是令人讨厌的,很难弄清的错误.
Secondly, it is all about consistency and code maintenance. What happens when you refactor MyClass
to be a subclass of some class where the designated initializer is actually critical? A nasty, hard to figure out, bug is what happens.
相关性,请注意,出于类似原因,几乎不建议使用+new
.它使重构变得乏味(该死!也必须拆开该呼叫站点!),而便利性因素却极小.
Of relevance, note that the use of +new
has been all but deprecated for a similar reason. It makes refactoring tedious (dammit! gotta break apart THIS call site, too!) and the convenience factor is exceedingly minimal.
这篇关于如果我在-init中什么也不做,是否与仅调用[MyClass alloc]一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!