Skip to main content

Loading Windows from Nib Files

·2 mins

This post summarizes what I learned when I wrote some code to load a PDF preview window from an external nib file. I’m sharing what I learned in case someone else runs into problems loading windows from external nib/xib files.

Short answer: NSWindowController is your friend. Call initWithWindowNibName: to load the window. Call showWindow: to show the window.

Subclassing NSWindowController #

You don’t have to subclass NSWindowController to load a window from a nib, but subclassing NSWindowController makes it easier to access the views and controls in the window. To create a subclass of NSWindowController, choose File > New > File in Xcode.

If you subclass NSWindowController and want to create outlets and actions in Interface Builder, make sure you set the class of the xib’s File’s Owner to your NSWindowController subclass.

Loading the Window #

To load the window from the nib file, call NSWindowController’s initWithWindowNibName: method. Supply the name of the nib file, minus the .nib file extension. The following code loads a window from a nib file named Preview.nib:

NSWindowController* previewWindow;
previewWindow = [[NSWindowController alloc] initWithWindowNibName:@"Preview"];

In this example I used NSWindowController. If you subclass NSWindowController, substitute the name of your subclass.

Showing the Window #

After loading the window, call NSWindowController’s showWindow: method to show the window. You can pass the object sending the message, but in most cases you can just pass nil, as in the following code:

[previewWindow showWindow:nil];

You must show the window before you can access the window’s views and controls. The views and controls are nil until you show the window.