objective-c - 在 init 方法中调用 [super init] 是否正确?

标签 objective-c winobjc

在 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/

相关文章:

ios - WinObjC 的 AFNetworking

linux - 在 Linux 上构建 WinObjC 应用程序

WinObjC 构建项目错误

ios - 如何在Visual Studio中创建空白WinObjc项目?

iphone - iOS 查找附近的其他设备(GPS 位置)

ios - 即使我不动也会得到不同的位置

ios - rangeOfString 方法调用导致无法识别的选择器错误

objective-c - @synchronized 锁定 iVar 和/或属性?

ios - 如何访问年龄限制家长控制 - iOS