NSWindow object manages a window, usually a window stored in a nib file.
- macOS 10.0+
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
NSDocument 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
NSWindow. The Application Kit will create one for you. However, if the default window controller is not sufficient, you can create a custom subclass of
NSWindow. For documents with multiple windows or panels, your document must create separate instances of
NSWindow (or of custom subclasses of
NSWindow), 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
NSWindow or separately created and configured
NSWindow objects are used.
You should create a subclass of
NSWindow 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
init initializers or the
init(window:) initializer. Which one depends on whether the window object originates in a nib file or is programmatically created.
NSWindow methods are most commonly overridden:
You can also override
load to get different nib-searching or nib-loading behavior, although there is usually no need to do this.