在 Microsoft 的 WinObjC UIApplication.mm 文件中(位于 https://github.com/Microsoft/WinObjC/blob/master/Frameworks/UIKit/UIApplication.mm ) init
UIApplication
都实现了方法和 WOCDisplayMode
.
这两个类' init
方法调用 [super init]
,或该系列方法中最终会导致调用 [super init]
的任何方法.除了 NSProxy
的初始化之外,我以前从未见过这个对象。
我在撰写本文时复制了 WOCDisplayMode
的实现以下供引用。
-(instancetype) init
{
_fixedWidth = 320.0f;
_fixedHeight = 480.0f;
_fixedAspectRatio = 0.0f;
_magnification = 1.0f;
_autoMagnification = TRUE;
_sizeUIWindowToFit = TRUE;
_operationMode = WOCOperationModePhone;
return self;
}
在我看来,这可能会产生许多问题;例如,如果 UIApplication
的父类(super class)之一, 比如 UIResponder
, 在某些时候覆盖了 init
本身,并设置 future 方法调用所依赖的内部状态。
为什么实现者选择不调用 [super init]
?这是一个合理的决定吗?它永远是正确的吗?
最佳答案
从这些类的作者的角度来看,这绝对像是一个错误。
NSProxy
不打电话 [super init]
因为它是一个抽象父类(super class)并且不继承自NSObject
.
自从他们实现 UIApplication
继承自 UIResponder
, 和 WOCDisplayMode
继承自 NSObject
他们应该调用[super init]
在这些类(class)中。
根据 Object Initialization 上的文档:
The requirement to invoke the superclass’s initializer as the first action is important. Recall that an object encapsulates not only the instance variables defined by its class but the instance variables defined by all of its ancestor classes. By invoking the initializer of super first, you help to ensure that the instance variables defined by classes up the inheritance chain are initialized first. The immediate superclass, in its initializer, invokes the initializer of its superclass, which invokes the main init... method of its superclass, and so on (see Figure 6-1). The proper order of initialization is critical because the later initializations of subclasses may depend on superclass-defined instance variables being initialized to reasonable values.
我建议将其记录为项目的一个问题。
关于objective-c - 在 init 方法中调用 [super init] 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31871381/