Search code examples
cocoaswiftappkit

How to initialize a NSWindowController in Swift?


I want to initialize a window controller object from a nib file, quite easy right? But I simply can't get it to work.

According to my previous experience in ObjC, I've written down the following code:

init()  {
    super.init(windowNibName: "SplitWindowController")
}

And in the app delegate file, I simply init and displays the window:

var myWindowController: MyWindowController = MyWindowController()
myWindowController.showWindow(self)
myWindowController.window.makeKeyAndOrderFront(nil)

But the compiler gives me this error: Must call a designated initializer of the superclass 'NSWindowController'. And according to the Swift version of NSWindowController definition, there are only 3 designated initializers, namely init(), init(window), init(coder). I don't know what to do next. Shall I build a NSCoder from a nib file, which I don't know how to do?


Solution

  • NSWindowController has 2 designated initializers:

    init(window: NSWindow!)
    init(coder: NSCoder!)
    

    When creating a subclass, you should invoke the designated initializer of its superclass. Recent versions of Xcode enforce this. Either via built-in language mechanism (Swift) or via NS_DESIGNATED_INITIALIZER macro (Objective-C).

    Swift additionally requires that you call the superclasses designated initializer when you override a convenience initializer.
    From the "Initialization: Designated Initializers and Convenience Initializers" section of Swift Programming Guide:

    If the initializer you are overriding is a convenience initializer, your override must call another designated initializer from its own subclass, as per the rules described above in Initializer Chaining.

    In your case, you should probably override init(window: NSWindow!) and call super's counterpart from there.