An NSApplication object manages an app’s main event loop in addition to resources used by all of that app’s objects.


Every app must have exactly one instance of NSApplication (or a subclass of NSApplication). Your program’s main() function should create this instance by invoking the shared() class method. After creating the NSApplication object, the main() function should load your app’s main nib file and then start the event loop by sending the NSApplication object a run() message. If you create an Application project in Xcode, this main() function is created for you. The main() function Xcode creates begins by calling a function named NSApplication​Main(), which is functionally similar to the following:

void NSApplicationMain(int argc, char *argv[]) {
    [NSApplication sharedApplication];
    [NSBundle loadNibNamed:@"myMain" owner:NSApp];
    [NSApp run];

The shared() class method initializes the display environment and connects your program to the window server and the display server. The NSApplication object maintains a list of all the NSWindow objects the app uses, so it can retrieve any of the app’s NSView objects. The shared() method also initializes the global variable NSApp, which you use to retrieve the NSApplication instance. shared() only performs the initialization once; if you invoke it more than once, it simply returns the NSApplication object it created previously.

The shared NSApplication object performs the important task of receiving events from the window server and distributing them to the proper NSResponder objects. NSApp translates an event into an NSEvent object, then forwards the NSEvent object to the affected NSWindow object. All keyboard and mouse events go directly to the NSWindow object associated with the event. The only exception to this rule is if the Command key is pressed when a key-down event occurs; in this case, every NSWindow object has an opportunity to respond to the event. When an NSWindow object receives an NSEvent object from NSApp, it distributes it to the objects in its view hierarchy.

NSApplication is also responsible for dispatching certain Apple events received by the app. For example, macOS sends Apple events to your app at various times, such as when the app is launched or reopened. NSApplication installs Apple event handlers to handle these events by sending a message to the appropriate object. You can also use the NSApple​Event​Manager class to register your own Apple event handlers. The application​Will​Finish​Launching(_:​) method is generally the best place to do so. For more information on how events are handled and how you can modify the default behavior, including information on working with Apple events in scriptable apps, see How Cocoa Applications Handle Apple Events in Cocoa Scripting Guide.

The NSApplication class sets up @autorelease block during initialization and inside the event loop—specifically, within its initialization (or shared()) and run() methods. Similarly, the methods AppKit adds to NSBundle employ @autorelease blocks during the loading of nib files. These @autorelease blocks aren’t accessible outside the scope of the respective NSApplication and NSBundle methods. Typically, an app creates objects either while the event loop is running or by loading objects from nib files, so this lack of access usually isn’t a problem. However, if you do need to use Cocoa classes within the main() function itself (other than to load nib files or to instantiate NSApplication), you should create an @autorelease block to contain the code using the classes.

The Delegate and Notifications

You can assign a Delegation to NSApp. The delegate responds to certain messages on behalf of NSApp. Some of these messages, such as application(_:​open​File:​), ask the delegate to perform an action. Another message, application​Should​Terminate(_:​), lets the delegate determine whether the app should be allowed to quit. The NSApplication class sends these messages directly to its delegate.

The NSApp also posts notifications to the app’s default notification center. Any object may register to receive one or more of the notifications posted by NSApp by sending the message add​Observer(_:​selector:​name:​object:​) to the default notification center (an instance of the NSNotification​Center class). The delegate of NSApp is automatically registered to receive these notifications if it implements certain delegate methods. For example, NSApp posts notifications when it is about to be done launching the app and when it is done launching the app (NSApplication​Will​Finish​Launching and NSApplication​Did​Finish​Launching). The delegate has an opportunity to respond to these notifications by implementing the methods application​Will​Finish​Launching(_:​) and application​Did​Finish​Launching(_:​). If the delegate wants to be informed of both events, it implements both methods. If it needs to know only when the app is finished launching, it implements only application​Did​Finish​Launching(_:​).

System Services

NSApplication interacts with the system services architecture to provide services to your app through the Services menu.

Subclassing Notes

You rarely should find a real need to create a custom NSApplication subclass. Unlike some object-oriented libraries, Cocoa does not require you to subclass NSApplication to customize app behavior. Instead it gives you many other ways to customize an app. This section discusses both some of the possible reasons to subclass NSApplication and some of the reasons not to subclass NSApplication.

To use a custom subclass of NSApplication, simply send shared() to your subclass rather than directly to NSApplication. If you create your app in Xcode, you can accomplish this by setting your custom app class to be the principal class. In Xcode, double-click the app target in the Groups and Files list to open the Info window for the target. Then display the Properties pane of the window and replace “NSApplication” in the Principal Class field with the name of your custom class. The NSApplication​Main function sends shared() to the principal class to obtain the global app instance (NSApp)—which in this case will be an instance of your custom subclass of NSApplication.

Methods to Override

Generally, you subclass NSApplication to provide your own special responses to messages that are routinely sent to the global app object (NSApp). NSApplication does not have primitive methods in the sense of methods that you must override in your subclass. Here are four methods that are possible candidates for overriding:

  • Override run() if you want the app to manage the main event loop differently than it does by default. (This a critical and complex task, however, that you should only attempt with good reason.)

  • Override send​Event(_:​) if you want to change how events are dispatched or perform some special event processing.

  • Override request​User​Attention(_:​) if you want to modify how your app attracts the attention of the user (for example, offering an alternative to the bouncing app icon in the Dock).

  • Override target(for​Action:​) to substitute another object for the target of an action message.

Special Considerations

The global app object uses @autorelease blocks in its run() method; if you override this method, you’ll need to create your own @autorelease blocks.

Do not override shared(). The default implementation, which is essential to app behavior, is too complex to duplicate on your own.

Alternatives to Subclassing

NSApplication defines numerous Delegation methods that offer opportunities for modifying specific aspects of app behavior. Instead of making a custom subclass of NSApplication, your app delegate may be able to implement one or more of these methods to accomplish your design goals. In general, a better design than subclassing NSApplication is to put the code that expresses your app’s special behavior into one or more custom objects called controllers. Methods defined in your controllers can be invoked from a small dispatcher object without being closely tied to the global app object.


Getting the Shared App Object

class func shared()

Returns the application instance, creating it if it doesn’t exist yet.

Configuring the App

func finish​Launching()

Activates the app, opens any files specified by the NSOpen user default, and unhighlights the app’s icon.

var application​Icon​Image:​ NSImage!

The image used for the app’s icon.

Terminating the App

func terminate(Any?)

Terminates the receiver.

func reply(to​Application​Should​Terminate:​ Bool)

Responds to NSTerminate​Later once the app knows whether it can terminate.

Handling Events

var current​Event:​ NSEvent?

The last event object that the app retrieved from the event queue.

func next​Event(matching:​ NSEvent​Mask, until:​ Date?, in​Mode:​ Run​Loop​Mode, dequeue:​ Bool)

Returns the next event matching a given mask, or nil if no such event is found before a specified expiration date.

func discard​Events(matching:​ NSEvent​Mask, before:​ NSEvent?)

Removes all events matching the given mask and generated before the specified event.

Managing the Event Loop

var is​Running:​ Bool

A Boolean value indicating whether the main event loop is running.

func run()

Starts the main event loop.

func stop(Any?)

Stops the main event loop.

func send​Event(NSEvent)

Dispatches an event to other objects.

func post​Event(NSEvent, at​Start:​ Bool)

Adds a given event to the receiver’s event queue.

Managing Remote Notifications

var enabled​Remote​Notification​Types:​ NSRemote​Notification​Type

The types of push notifications that the app accepts.

func register​For​Remote​Notifications(matching:​ NSRemote​Notification​Type)

Register to receive notifications of the specified types from a provider via Apple Push Notification service.

func unregister​For​Remote​Notifications()

Unregister for notifications received from Apple Push Notification service.

Managing Modal Windows

func run​Modal(for:​ NSWindow)

Starts a modal event loop for the specified window.

func stop​Modal()

Stops a modal event loop.

func stop​Modal(with​Code:​ Int)

Stops a modal event loop, allowing you to return a custom result code.

func begin​Modal​Session(for:​ NSWindow)

Sets up a modal session with the given window and returns a pointer to the NSModal​Session structure representing the session.

func run​Modal​Session(NSModal​Session)

Runs a given modal session, as defined in a previous invocation of begin​Modal​Session(for:​).

var modal​Window:​ NSWindow?

The modal window displayed by the app.

func end​Sheet(NSWindow)

Ends a document modal session by specifying the sheet window.

func end​Sheet(NSWindow, return​Code:​ Int)

Ends a document modal session by specifying the sheet window.


Managing Panels

func order​Front​Color​Panel(Any?)

Brings up the color panel, an instance of NSColor​Panel.

func order​Front​Standard​About​Panel(options:​ [String :​ Any] = [:​])

Displays a standard About window with information from a given options dictionary.

func run​Page​Layout(Any?)

Displays the receiver’s page layout panel, an instance of NSPage​Layout.

Window Restoration

func extend​State​Restoration()

Allows an app to extend its state restoration period.

func complete​State​Restoration()

Completes the extended state restoration.

User Interface Layout Direction

Managing Windows

var key​Window:​ NSWindow?

The window that currently receives keyboard events.

var main​Window:​ NSWindow?

The app’s main window.

func window(with​Window​Number:​ Int)

Returns the window corresponding to the specified window number.

var windows:​ [NSWindow]

An array of the app’s window objects.

func make​Windows​Perform(Selector, in​Order:​ Bool)

Sends the specified message to each of the app’s window objects until one returns a non-nil value.


Minimizing Windows

func miniaturize​All(Any?)

Miniaturizes all the receiver’s windows.

Hiding Windows

var is​Hidden:​ Bool

A Boolean value indicating whether the app is hidden.

func hide(Any?)

Hides all the receiver’s windows, and the next app in line is activated.

func unhide(Any?)

Restores hidden windows to the screen and makes the receiver active.

func unhide​Without​Activation()

Restores hidden windows without activating their owner (the receiver).

Updating Windows

func update​Windows()

Sends an update() message to each onscreen window.

func set​Windows​Need​Update(Bool)

Sets whether the receiver’s windows need updating when the receiver has finished processing the current event.

Managing Window Layers

func prevent​Window​Ordering()

Suppresses the usual window ordering in handling the most recent mouse-down event.

func arrange​In​Front(Any?)

Arranges windows listed in the Window menu in front of all other windows.

Accessing the Main Menu

var main​Menu:​ NSMenu?

The app’s main menu bar.

Managing the Window Menu

var windows​Menu:​ NSMenu?

The Window menu of the app.

func add​Windows​Item(NSWindow, title:​ String, filename:​ Bool)

Adds an item to the Window menu for a given window.

func change​Windows​Item(NSWindow, title:​ String, filename:​ Bool)

Changes the item for a given window in the Window menu to a given string.

func remove​Windows​Item(NSWindow)

Removes the Window menu item for a given window.

func update​Windows​Item(NSWindow)

Updates the Window menu item for a given window to reflect the edited status of that window.

Accessing the Dock Tile

var dock​Tile:​ NSDock​Tile

The app’s Dock tile.

Managing the Services Menu

func register​Services​Menu​Send​Types([String], return​Types:​ [String])

Registers the pasteboard types the receiver can send and receive in response to service requests.

var services​Menu:​ NSMenu?

The app’s Services menu.

Managing the App’s Activation Status

var is​Active:​ Bool

A Boolean value indicating whether this is the active app.

func activate(ignoring​Other​Apps:​ Bool)

Makes the receiver the active app.

func deactivate()

Deactivates the receiver.

Hiding Apps

func hide​Other​Applications(Any?)

Hides all apps, except the receiver.

func unhide​All​Applications(Any?)

Unhides all apps, including the receiver.

Providing Services

func valid​Requestor(for​Send​Type:​ String, return​Type:​ String)

Indicates whether the receiver can send and receive the specified pasteboard types.

var services​Provider:​ Any?

The object that provides the services the current app advertises in the Services menu of other apps.

Displaying Help

func show​Help(Any?)

If your project is properly registered, and the necessary keys have been set in the property list, this method launches Help Viewer and displays the first page of your app’s help book.

func activate​Context​Help​Mode(Any?)

Places the receiver in context-sensitive help mode.

var help​Menu:​ NSMenu?

The help menu used by the app.

Managing Threads

class func detach​Drawing​Thread(Selector, to​Target:​ Any, with:​ Any?)

Creates and executes a new thread based on the specified target and selector.

Posting Actions

func `try`(to​Perform:​ Selector, with:​ Any?)

Dispatches an action message to the specified target.

func send​Action(Selector, to:​ Any?, from:​ Any?)

Sends the given action message to the given target.

func target(for​Action:​ Selector)

Returns the object that receives the action message specified by the given selector

func target(for​Action:​ Selector, to:​ Any?, from:​ Any?)

Searches for an object that can receive the message specified by the given selector.

Drawing Windows

var context:​ NSGraphics​Context?

The graphics context associated with the app.


Logging Exceptions

func report​Exception(NSException)

Logs a given exception by calling NSLog().

Managing User Attention Requests

func cancel​User​Attention​Request(Int)

Cancels a previous user attention request.

func reply(to​Open​Or​Print:​ NSApplication​Delegate​Reply)

Handles errors that might occur when the user attempts to open or print files.

Keyboard Accessibility

var is​Full​Keyboard​Access​Enabled:​ Bool

A Boolean value indicating whether Full Keyboard Access is enabled in the Keyboard preference pane.

Presentation Options

var current​System​Presentation​Options:​ NSApplication​Presentation​Options

The set of app presentation options that are currently in effect for the system.

var presentation​Options:​ NSApplication​Presentation​Options

The presentation options that should be in effect for the system when this app is active.

Activation Policy

func activation​Policy()

Returns the app’s activation policy.

func set​Activation​Policy(NSApplication​Activation​Policy)

Attempts to modify the app's activation policy.

Managing Relaunch on Login

func disable​Relaunch​On​Login()

Disables relaunching the app on login.

func enable​Relaunch​On​Login()

Enables relaunching the app on login.

Accessing Occlusion State


var ordered​Documents:​ [NSDocument]

An array of document objects arranged according to the front-to-back ordering of their associated windows.

var ordered​Windows:​ [NSWindow]

An array of window objects arranged according to their front-to-back ordering on the screen.

func application(NSApplication, delegate​Handles​Key:​ String)

Sent by Cocoa’s built-in scripting support during execution of get or set script commands to find out if the delegate can handle operations on the specified key-value key.



A global constant for the shared app instance.


Specifies the directional flow of the user interface. These constants are returned by user​Interface​Layout​Direction.


These constants specify the level of severity of a user attention request and are used by cancel​User​Attention​Request(_:​) and request​User​Attention(_:​).


These constants indicate whether or not a copy or print operation was successful, was cancelled, or failed. These constants are used by the reply(to​Open​Or​Print:​) method.


Constants that control the presentation of the app, typically for fullscreen apps such as games or kiosks.


These constants define whether an app should terminate and are used by the delegate method application​Should​Terminate(_:​).

Run loop modes

These loop mode constants are defined by NSApplication.

NSApplication​Did​Finish​Launching User Info Keys

The following constants define the keys that can be present in the NSApplication​Did​Finish​Launching.


These constants determine whether apps launched by remote notifications display a badge.


This constant indicates whether at least part of any window owned by this app is visible.


This constant indicates a window ordering.


This constant identifies the installed version of the AppKit framework.

App​Kit framework version numbers

You can use the following constants to determine if you are using a version of the AppKit framework newer than the version delivered in OS X v10.0.


These notifications apply to NSApplication. See Notifications in NSWorkspace for additional, similar notifications.

static let NSApplication​Did​Become​Active:​ NSNotification.Name

Posted immediately after the app becomes active.

static let NSApplication​Did​Change​Screen​Parameters:​ NSNotification.Name

Posted when the configuration of the displays attached to the computer is changed.

static let NSApplication​Did​Finish​Launching:​ NSNotification.Name

Posted at the end of the finish​Launching() method to indicate that the app has completed launching and is ready to run.

static let NSApplication​Did​Hide:​ NSNotification.Name

Posted at the end of the hide(_:​) method to indicate that the app is now hidden.

static let NSApplication​Did​Resign​Active:​ NSNotification.Name

Posted immediately after the app gives up its active status to another app.

static let NSApplication​Did​Unhide:​ NSNotification.Name

Posted at the end of the unhide​Without​Activation() method to indicate that the app is now visible.

static let NSApplication​Did​Update:​ NSNotification.Name

Posted at the end of the update​Windows() method to indicate that the app has finished updating its windows.

static let NSApplication​Will​Become​Active:​ NSNotification.Name

Posted immediately before the app becomes active.

static let NSApplication​Will​Finish​Launching:​ NSNotification.Name

Posted at the start of the finish​Launching() method to indicate that the app has completed its initialization process and is about to finish launching.

static let NSApplication​Will​Hide:​ NSNotification.Name

Posted at the start of the hide(_:​) method to indicate that the app is about to be hidden.

static let NSApplication​Will​Resign​Active:​ NSNotification.Name

Posted immediately before the app gives up its active status to another app.

static let NSApplication​Will​Terminate:​ NSNotification.Name

Posted by the terminate(_:​) method to indicate that the app will terminate.

static let NSApplication​Will​Unhide:​ NSNotification.Name

Posted at the start of the unhide​Without​Activation() method to indicate that the app is about to become visible.

static let NSApplication​Will​Update:​ NSNotification.Name

Posted at the start of the update​Windows() method to indicate that the app is about to update its windows.