0
votes

Isn't functionality put in a convenience init - unusable in sub-classes?

If so, why are the Cocoa's interfaces for Swift defining so many initializers as convenience.

For example - I have a sub-class of NSWindowController and I would like to create a designated init, which will not get any parameters and should directly know what NIB file to instantiate with.

But I don't have any access to super.init's/methods to get the already implemented behaviour and build up on it. Here is the definition of the inits of NSWindowController:

class NSWindowController : NSResponder, NSCoding, NSSeguePerforming, NSObjectProtocol {
    init(window: NSWindow?)
    init?(coder: NSCoder)

    convenience init(windowNibName: String)
    convenience init(windowNibName: String, owner: AnyObject)
    convenience init(windowNibPath: String, owner: AnyObject)
    // ...
}

Instead I am forced to reimplement the NIB loading, thus duplicating and potentially getting it wrong.

Edit:

Here is a small passage from a blogpost by Mike Ash, mentioning NSWindowController subclasses and the reasoning behind what I do in my case is exactly the same:

NSWindowController provides a initWithWindowNibName: method. However, your subclass is built to work with only a single nib, so it's pointless to make clients specify that nib name. Instead, we'll provide a plain init method that does the right thing internally. Simply override it to call super and provide the nib name:

- (id)init
{
    return [super initWithWindowNibName: @"MAImportantThingWindow"];
}

So it's possible in ObjectiveC, but how can this be done in Swift?

1

1 Answers

1
votes

Convenience initializers are inherited in subclasses. They can be overriden, too.

In order to call init(windowNibName: String), you need to declare a convenience initializer to call it from, and you should call it on self, rather than super:

class MAImportantThingWindowController : NSWindowController {

    override convenience init() {
        self.init(windowNibName: "MAImportantThingWindow")
    }
}