A view controller manages a view, typically loaded from a nib file.
- macOS 10.5+
This management includes:
Memory management of top-level objects similar to that performed by the
NSWindowControllerclass, taking the same care to prevent reference cycles when controls are bound to the nib file's owner.
Declaring a generic
viewproperty, to make it easy to establish bindings in the nib to an object that isn't yet known at nib-loading time or readily available to the code that's doing the nib loading.
Implementing the key-value binding NSEditor informal protocol, so that apps using a view controller can easily make bound controls in the views commit or discard changes by the user.
In macOS 10.10 and later, a view controller offers a full set of lifecycle methods, allowing you to manage the content of a window in a way that is on a par with iOS view controller management. These methods, presented in order here to reflect a typical cycle, are:
User interaction cycle:
In addition, in macOS 10.10 and later, a view controller participates in the responder chain. You can implement action methods directly in the view controller. Corresponding actions that originate in the view controller’s view proceed up the responder chain and are handled by those methods.
Prior to OS X v10.10, a typical usage pattern for loading a nib file was to subclass
NSViewController and override its
loadView() method to call
[super loadView]. But in macOS 10.10 and later, the
loadView() method automatically looks for a nib file with the same name as the view controller. To take advantage of this behavior, name a nib file after its corresponding view controller and pass
nil to both parameters of the
A view controller employs lazy loading of its view: Immediately after a view controller is loaded into memory, the value of its
isViewLoaded property is
false. The value changes to
true after the
loadView() method returns and just before the system calls the
A view controller is meant to be highly reusable, such as for dynamically representing various objects. For example, the
addAccessoryController(_:) methods of the
NSPrintPanel classes take an
NSViewController instance as the argument, and set the
view property to the
NSPrintInfo object that is to be shown to the user. This allows a developer to easily create new printing accessory views using bindings and the
NSPrintInfo class's key-value coding and key-value observing compliance. When the user dismisses a printing dialog, the
NSPrintPanel classes each send NSEditor messages to each accessory view controller to ensure that the user's changes have been committed or discarded properly. The titles of the accessories are retrieved from the view controllers and shown to the user in pulldown menus that the user can choose from.