NSWindowController object manages a window, usually a window stored in a nib file.
- macOS 10.10+
This management entails:
Loading and displaying the window
Closing the window when appropriate
Customizing the window’s title
Storing the window’s frame (size and location) in the defaults database
Cascading the window in relation to other document windows of the application
A window controller can manage a window by itself or as a role player in the Application Kit’s document-based architecture, which also includes
NSDocumentController objects. In this architecture, a window controller is created and managed by a “document” (an instance of an
NSDocument subclass) and, in turn, keeps a reference to the document.
The relationship between a window controller and a nib file is important. Although a window controller can manage a programmatically created window, it usually manages a window in a nib file. The nib file can contain other top-level objects, including other windows, but the window controller’s responsibility is this primary window. The window controller is usually the owner of the nib file, even when it is part of a document-based application. Regardless of who is the file’s owner, the window controller is responsible for freeing all top-level objects in the nib file it loads.
For simple documents—that is, documents with only one nib file containing a window—you need do little directly with
NSWindowController. The Application Kit will create one for you. However, if the default window controller is not sufficient, you can create a custom subclass of
NSWindowController. For documents with multiple windows or panels, your document must create separate instances of
NSWindowController (or of custom subclasses of
NSWindowController), one for each window or panel. An example is a CAD application that has different windows for side, top, and front views of drawn objects. What you do in your
NSDocument subclass determines whether the default
NSWindowController or separately created and configured
NSWindowController objects are used.
You should create a subclass of
NSWindowController when you want to augment the default behavior, such as to give the window a custom title or to perform some setup tasks before the window is loaded. In your class’s initialization method, be sure to invoke on
super either one of the
initWithWindowNibName:... initializers or the
init(window:) initializer. Which one depends on whether the window object originates in a nib file or is programmatically created.
NSWindowController methods are most commonly overridden:
You can also override
loadWindow() to get different nib-searching or nib-loading behavior, although there is usually no need to do this.