Class

NSApplication

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

Overview

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 NSApplicationMain(), 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 NSAppleEventManager class to register your own Apple event handlers. The applicationWillFinishLaunching(_:) 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(_:openFile:), ask the delegate to perform an action. Another message, applicationShouldTerminate(_:), 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 addObserver(_:selector:name:object:) to the default notification center (an instance of the NSNotificationCenter 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 (NSApplicationWillFinishLaunching and NSApplicationDidFinishLaunching). The delegate has an opportunity to respond to these notifications by implementing the methods applicationWillFinishLaunching(_:) and applicationDidFinishLaunching(_:). 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 applicationDidFinishLaunching(_:).

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 NSApplicationMain 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 sendEvent(_:) if you want to change how events are dispatched or perform some special event processing.

  • Override requestUserAttention(_:) 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(forAction:) 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.

Symbols

Getting the Shared App Object

class func shared()

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

Configuring the App

func finishLaunching()

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

var delegate: NSApplicationDelegate?

The app delegate object.

var applicationIconImage: NSImage!

The image used for the app’s icon.

Terminating the App

func terminate(Any?)

Terminates the receiver.

func reply(toApplicationShouldTerminate: Bool)

Responds to NSTerminateLater once the app knows whether it can terminate.

Handling Events

var currentEvent: NSEvent?

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

func nextEvent(matching: NSEventMask, until: Date?, inMode: RunLoopMode, dequeue: Bool)

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

func discardEvents(matching: NSEventMask, before: NSEvent?)

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

Managing the Event Loop

var isRunning: 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 sendEvent(NSEvent)

Dispatches an event to other objects.

func postEvent(NSEvent, atStart: Bool)

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

Managing Remote Notifications

var enabledRemoteNotificationTypes: NSRemoteNotificationType

The types of push notifications that the app accepts.

func registerForRemoteNotifications(matching: NSRemoteNotificationType)

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

func unregisterForRemoteNotifications()

Unregister for notifications received from Apple Push Notification service.

Managing Modal Windows

func runModal(for: NSWindow)

Starts a modal event loop for a given window.

func stopModal()

Stops a modal event loop.

func stopModal(withCode: Int)

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

func abortModal()

Aborts the event loop started by runModal(for:) or runModalSession(_:).

func beginModalSession(for: NSWindow)

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

func runModalSession(NSModalSession)

Runs a given modal session, as defined in a previous invocation of beginModalSession(for:).

var modalWindow: NSWindow?

The modal window displayed by the app.

func endModalSession(NSModalSession)

Finishes a modal session.

func endSheet(NSWindow)

Ends a document modal session by specifying the sheet window.

Deprecated
func endSheet(NSWindow, returnCode: Int)

Ends a document modal session by specifying the sheet window.

Deprecated

Managing Panels

func orderFrontColorPanel(Any?)

Brings up the color panel, an instance of NSColorPanel.

func orderFrontStandardAboutPanel(Any?)

Displays a standard About window.

func orderFrontStandardAboutPanel(options: [String : Any] = [:])

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

func orderFrontCharacterPalette(Any?)

Opens the character palette.

func runPageLayout(Any?)

Displays the receiver’s page layout panel, an instance of NSPageLayout.

Window Restoration

func extendStateRestoration()

Allows an app to extend its state restoration period.

func completeStateRestoration()

Completes the extended state restoration.

User Interface Layout Direction

var userInterfaceLayoutDirection: NSUserInterfaceLayoutDirection

The layout direction of the user interface.

Managing Windows

var keyWindow: NSWindow?

The window that currently receives keyboard events.

var mainWindow: NSWindow?

The app’s main window.

func window(withWindowNumber: Int)

Returns the window corresponding to the specified window number.

var windows: [NSWindow]

An array of the app’s window objects.

func makeWindowsPerform(Selector, inOrder: Bool)

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

Deprecated

Minimizing Windows

func miniaturizeAll(Any?)

Miniaturizes all the receiver’s windows.

Hiding Windows

var isHidden: 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 unhideWithoutActivation()

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

Updating Windows

func updateWindows()

Sends an update() message to each onscreen window.

func setWindowsNeedUpdate(Bool)

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

Managing Window Layers

func preventWindowOrdering()

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

func arrangeInFront(Any?)

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

Accessing the Main Menu

var mainMenu: NSMenu?

The app’s main menu bar.

Managing the Window Menu

var windowsMenu: NSMenu?

The Window menu of the app.

func addWindowsItem(NSWindow, title: String, filename: Bool)

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

func changeWindowsItem(NSWindow, title: String, filename: Bool)

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

func removeWindowsItem(NSWindow)

Removes the Window menu item for a given window.

func updateWindowsItem(NSWindow)

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

Accessing the Dock Tile

var dockTile: NSDockTile

The app’s Dock tile.

Managing the Services Menu

func registerServicesMenuSendTypes([String], returnTypes: [String])

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

var servicesMenu: NSMenu?

The app’s Services menu.

Managing the App’s Activation Status

var isActive: Bool

A Boolean value indicating whether this is the active app.

func activate(ignoringOtherApps: Bool)

Makes the receiver the active app.

func deactivate()

Deactivates the receiver.

Hiding Apps

func hideOtherApplications(Any?)

Hides all apps, except the receiver.

func unhideAllApplications(Any?)

Unhides all apps, including the receiver.

Providing Services

func validRequestor(forSendType: String, returnType: String)

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

var servicesProvider: Any?

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

Displaying Help

func showHelp(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 activateContextHelpMode(Any?)

Places the receiver in context-sensitive help mode.

var helpMenu: NSMenu?

The help menu used by the app.

Managing Threads

class func detachDrawingThread(Selector, toTarget: Any, with: Any?)

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

Posting Actions

func `try`(toPerform: Selector, with: Any?)

Dispatches an action message to the specified target.

func sendAction(Selector, to: Any?, from: Any?)

Sends the given action message to the given target.

func target(forAction: Selector)

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

func target(forAction: Selector, to: Any?, from: Any?)

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

Drawing Windows

var context: NSGraphicsContext?

The graphics context associated with the app.

Deprecated

Logging Exceptions

func reportException(NSException)

Logs a given exception by calling NSLog().

Managing User Attention Requests

func cancelUserAttentionRequest(Int)

Cancels a previous user attention request.

func reply(toOpenOrPrint: NSApplicationDelegateReply)

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

Keyboard Accessibility

var isFullKeyboardAccessEnabled: Bool

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

Presentation Options

var currentSystemPresentationOptions: NSApplicationPresentationOptions

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

var presentationOptions: NSApplicationPresentationOptions

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

Activation Policy

func activationPolicy()

Returns the app’s activation policy.

func setActivationPolicy(NSApplicationActivationPolicy)

Attempts to modify the app's activation policy.

Spotlight for Help

Managing Relaunch on Login

func disableRelaunchOnLogin()

Disables relaunching the app on login.

func enableRelaunchOnLogin()

Enables relaunching the app on login.

Accessing Occlusion State

var occlusionState: NSApplicationOcclusionState

The occlusion state of the app.

Scripting

var orderedDocuments: [NSDocument]

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

var orderedWindows: [NSWindow]

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

func application(NSApplication, delegateHandlesKey: 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.

Constants

NSApp

A global constant for the shared app instance.

NSUserInterfaceLayoutDirection

Specifies the directional flow of the user interface. These constants are returned by userInterfaceLayoutDirection.

NSUpdateWindowsRunLoopOrdering

This constant is used by the NSRunLoop method perform(_:target:argument:order:modes:).

NSRequestUserAttentionType

These constants specify the level of severity of a user attention request and are used by cancelUserAttentionRequest(_:) and requestUserAttention(_:).

NSApplicationDelegateReply

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

NSApplicationPresentationOptions

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

NSApplicationTerminateReply

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

NSApplicationPrintReply

These constants are returned by the delegate method application(_:printFiles:withSettings:showPrintPanels:).

Run loop modes

These loop mode constants are defined by NSApplication.

NSApplicationDidFinishLaunching User Info Keys

The following constants define the keys that can be present in the NSApplicationDidFinishLaunching.

NSRemoteNotificationType

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

NSApplicationOcclusionState

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

NSWindowListOptions

This constant indicates a window ordering.

NSAppKitVersionNumber

This constant identifies the installed version of the AppKit framework.

AppKit 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.

Notifications

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

static let NSApplicationDidBecomeActive: NSNotification.Name

Posted immediately after the app becomes active.

static let NSApplicationDidChangeScreenParameters: NSNotification.Name

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

static let NSApplicationDidFinishLaunching: NSNotification.Name

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

static let NSApplicationDidHide: NSNotification.Name

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

static let NSApplicationDidResignActive: NSNotification.Name

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

static let NSApplicationDidUnhide: NSNotification.Name

Posted at the end of the unhideWithoutActivation() method to indicate that the app is now visible.

static let NSApplicationDidUpdate: NSNotification.Name

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

static let NSApplicationWillBecomeActive: NSNotification.Name

Posted immediately before the app becomes active.

static let NSApplicationWillFinishLaunching: NSNotification.Name

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

static let NSApplicationWillHide: NSNotification.Name

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

static let NSApplicationWillResignActive: NSNotification.Name

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

static let NSApplicationWillTerminate: NSNotification.Name

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

static let NSApplicationWillUnhide: NSNotification.Name

Posted at the start of the unhideWithoutActivation() method to indicate that the app is about to become visible.

static let NSApplicationWillUpdate: NSNotification.Name

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

static let NSApplicationDidFinishRestoringWindows: NSNotification.Name

Posted when the app is finished restoring windows.

static let NSApplicationDidChangeOcclusionState: NSNotification.Name

Posted when the app’s occlusion state changes.