Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSWindowController designated initializer puzzle

Tags:

macos

swift

cocoa

I'm trying to make this code work:

class MyWindowController: NSWindowController
{
  let thing: Thing

  convenience init(thing: Thing)
  {
    self.thing = thing

    super.init(windowNibName: NSNib.Name(rawValue: "MyNib"))
  }
}

The problem, of course, is that a convenience initializer can't call init from a superclass. So how do I initialize my thing and still be able to call init(windowNibName:), which is itself a convenience initializer? I'd rather not have to re-implement the nib loading myself, but how do I avoid it if I can only use designated initializers?

like image 425
Uncommon Avatar asked Dec 03 '25 23:12

Uncommon


1 Answers

According to the NSWindowController documentation:

You can also implement an NSWindowController subclass to avoid requiring client code to get the corresponding nib's filename and pass it to init(windowNibName:) or init(windowNibName:owner:) when instantiating the window controller. The best way to do this is to override windowNibName to return the nib's filename and instantiate the window controller by passing nil to init(window:). Using the init(window:) designated initializer simplifies compliance with Swift initializer requirements.

You can implement your class as:

class MyWindowController: NSWindowController
{
    let thing: Thing

    override var windowNibName: NSNib.Name? {
        return NSNib.Name(rawValue: "MyNib")
    }

    init(thing: Thing) {
        self.thing = thing

        super.init(window: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
like image 110
rmaddy Avatar answered Dec 06 '25 16:12

rmaddy