Martin Martin - 2 years ago 323
Swift Question

Subclassing NSWindowController in Swift and init(windowNibName)

I am trying to start a new document based Cocoa project in Swift and want to create a subclass of

(as recommended in Apple's guides on document based apps). In ObjC you would make an instance of an
subclass sending the
message, which was implemented accordingly, calling the superclasses method.

In Swift
is only available as an convenience initializer, the designated initializer of
which obviously wants me to pass in a window.

I cannot call
from my subclass, because it is not the designated initializer, so I obviously have to implement
convenience init(windowNibName)
, which in turn needs to call
. But if all I have is my nib file, how do I access the nib file's window to send to that initializer?

Answer Source

You need to override either all three designated initializers of NSWindowController (init(), init(window) and init(coder)), or none of them, in which case your subclass will automatically inherit init(windowNibName) and all others convenience initializers and you will be able to construct it using superclass's convenience initializer:

// this overrides none of designated initializers
class MyWindowController: NSWindowController {
    override func windowDidLoad() {

// this one overrides all of them
// Awkwardly enough, I see only two initializers 
// when viewing `NSWindowController` source from Xcode, 
// but I have to also override `init()` to make these rules apply.
// Seems like a bug.
class MyWindowController: NSWindowController

    init(window: NSWindow!)
        super.init(window: window)

    init(coder: NSCoder!)
        super.init(coder: coder)

    override func windowDidLoad() {

// this will work with either of the above
let mwc: MyWindowController! = MyWindowController(windowNibName: "MyWindow")

This is covered by "Initialization / Automatic Initializer Inheritance" in the language guide:

However, superclass initializers are automatically inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it is safe to do so.

Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:

Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

Rule 2 If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download