Search code examples
objective-cwinobjc

Is not calling [super init] in the init method ever correct?


In Microsoft's WinObjC UIApplication.mm file (at https://github.com/Microsoft/WinObjC/blob/master/Frameworks/UIKit/UIApplication.mm) the init method is implemented for both UIApplication and WOCDisplayMode.

Neither class' init method calls [super init], or any method from that family of methods that would eventually result in a call to [super init]. I've never seen this before, apart from the initialization of NSProxy objects.

I've reproduced the implementation as of this writing of WOCDisplayMode below for reference.

-(instancetype) init
{
    _fixedWidth = 320.0f;
    _fixedHeight = 480.0f;
    _fixedAspectRatio = 0.0f;
    _magnification = 1.0f;
    _autoMagnification = TRUE;
    _sizeUIWindowToFit = TRUE;
    _operationMode = WOCOperationModePhone;
    return self;
}

It seems to me that this could create a number of problems; for example, if one of the superclasses of UIApplication, like UIResponder, at some point overrode init itself, and set up internal state that future method calls depended on.

Why might the implementor have elected not to call [super init]? Is this ever a justifiable decision? Is it ever the correct one?


Solution

  • This definitely seems like an error on behalf of the author(s) of those classes.

    NSProxy does not call [super init] because it is an abstract superclass and does not inherit from NSObject.

    Since their implementation of UIApplication inherits from UIResponder, and WOCDisplayMode inherits from NSObject they should be calling [super init] in these classes.

    According to the documentation on 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.

    I would recommend logging it as an issue on the project.