5

In a test Swift project, I am subclassing NSWindowController. My NSWindowController subclass is designed to work with a particular Nib file. It is desirable, then, that when my window controller is initialized, the nib file is automatically loaded by the window controller instance. In Objective-C, this was achieved by doing:

@implementation MyWindowController

- (id)init {
    self = [super initWithWindowNibName:"MyWindowNib"]
    if (self) {
        // whatever
    }
    return self
}

@end

Now, in Swift this is not possible: init() cannot call super.init(windowNibName:), because the later is declared not as a designated initializer, but as a convenience one by NSWindowController.

How can this be done in Swift? I don't see a strightforward way of doing it.

P.S.: I have seen other questions regarding this topic, but, as long as I've been able to understand, the solutions all point to initialize the Window Controller by calling init(windowNibName:). Please note that this is not the desired beheaviour. The Window Controller should be initialized with init(), and it should be the Window Controller itself who "picks up" its Nib file and loads it.

George
  • 1,235
  • 10
  • 23

2 Answers2

5

If you use the init() just to call super.init(windowNibName:), you could instead just override the windowNibName variable.

override var windowNibName: String  {
    get {
        return "MyWindowNib"
    }
}

Then there should be no need to mess with the initializers.

nrms
  • 81
  • 1
  • 3
  • In Swift 4, better like this: override var windowNibName: NSNib.Name? {get { return NSNib.Name(rawValue: "MyWindowNib") }} – Aarhus88 Sep 20 '17 at 17:44
  • @Aarhus88 Doesn't work: Property 'windowNibName' with type 'NSNib.Name?' (aka 'Optional') cannot override a property with type 'String?' – Extra Savoir-Faire Apr 10 '18 at 14:00
0

You can create your own convenience initializer instead:

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

You should instead opt in to replacing all designated initializers in your subclass, simply delegating to super where appropriate. Confer https://stackoverflow.com/a/24220904/1460929

Community
  • 1
  • 1
ctietze
  • 2,805
  • 25
  • 46