NSApplication Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AppKit.framework
Availability
Available in OS X v10.0 and later.
Declared in
NSApplication.h
NSApplicationScripting.h
NSColorPanel.h
NSHelpManager.h
NSPageLayout.h
NSUserInterfaceItemSearching.h
NSWindowRestoration.h
Companion guides
Related sample code

Class at a Glance

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

Principal Attributes

Commonly Used Methods

keyWindow

Returns an NSWindow object representing the key window.

mainWindow

Returns the application’s main window.

registerServicesMenuSendTypes:returnTypes:

Specifies which services are valid for this application.

runModalForWindow:

Runs a modal event loop for the specified NSWindow object.

Overview

The NSApplication class provides the central framework for your application’s execution.

Every application must have exactly one instance of NSApplication (or a subclass of NSApplication). Your program’s main() function should create this instance by invoking the sharedApplication class method. After creating the NSApplication object, the main() function should load your application’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 sharedApplication 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 application uses, so it can retrieve any of the application’s NSView objects. sharedApplication also initializes the global variable NSApp, which you use to retrieve the NSApplication instance. sharedApplication only performs the initialization once; if you invoke it more than once, it simply returns the NSApplication object it created previously.

NSApplication 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 application. For example, OS X sends Apple events to your application at various times, such as when the application 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 applications, 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 sharedApplication) and run methods. Similarly, the methods the Application Kit 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 application 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 delegate 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 application should be allowed to quit. The NSApplication class sends these messages directly to its delegate.

The NSApp also posts notifications to the application’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 application and when it is done launching the application (NSApplicationWillFinishLaunchingNotification and NSApplicationDidFinishLaunchingNotification). 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 application is finished launching, it implements only applicationDidFinishLaunching:.

System Services

NSApplication interacts with the system services architecture to provide services to your application 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 create a custom application class to customize application behavior. Instead it gives you many other ways to customize an application. 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 sharedApplication to your subclass rather than directly to NSApplication. If you create your application in Xcode, you can accomplish this by setting your custom application class to be the principal class. In Xcode, double-click the application 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 sharedApplication to the principal class to obtain the global application 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 application 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:

Special Considerations

The global application 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 sharedApplication. The default implementation, which is essential to application behavior, is too complex to duplicate on your own.

Alternatives to Subclassing

NSApplication defines numerous delegate methods that offer opportunities for modifying specific aspects of application behavior. Instead of making a custom subclass of NSApplication, your application 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 application’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 application object.

Tasks

Getting the Application

Configuring Applications

Launching Applications

Terminating Applications

Managing Active Status

Window Restoration

Hiding Applications

Managing the Event Loop

Handling Events

Posting Events

Managing Sheets

Managing Windows

Minimizing Windows

User Interface Layout Direction

Hiding Windows

Updating Windows

Managing Window Layers

Accessing the Main Menu

Managing the Window Menu

Accessing the Dock Tile

Managing the Services Menu

Providing Services

Managing Panels

Displaying Help

Managing Threads

Posting Actions

Drawing Windows

Logging Exceptions

Scripting

Managing User Attention Requests

Keyboard Accessibility

Presentation Options

Activation Policy

Spotlight for Help

Managing Relaunch on Login

Managing Remote Notifications

Accessing Occlusion State

Deprecated

Class Methods

detachDrawingThread:toTarget:withObject:

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

+ (void)detachDrawingThread:(SEL)selector toTarget:(id)target withObject:(id)argument
Parameters
selector

The selector whose code you want to execute in the new thread.

target

The object that defines the specified selector.

argument

An optional argument you want to pass to the selector.

Discussion

This method is a convenience wrapper for the detachNewThreadSelector:toTarget:withObject: method of NSThread. This method automatically creates an @autoreleasepool block for the new thread before invoking selector.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

sharedApplication

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

+ (NSApplication *)sharedApplication
Return Value

The shared application object.

Discussion

This method also makes a connection to the window server and completes other initialization. Your program should invoke this method as one of the first statements in main(); this invoking is done for you if you create your application with Xcode. To retrieve the NSApplication instance after it has been created, use the global variable NSApp or invoke this method.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

Instance Methods

abortModal

Aborts the event loop started by runModalForWindow: or runModalSession:.

- (void)abortModal
Discussion

When stopped with this method, runModalForWindow: and runModalSession: return NSModalResponseAbort.

abortModal must be used instead of stopModal or stopModalWithCode: when you need to stop a modal event loop from anywhere other than a callout from that event loop. In other words, if you want to stop the loop in response to a user’s actions within the modal window, use stopModal; otherwise, use abortModal. For example, use abortModal when running in a different thread from the Application Kit’s main thread or when responding to an NSTimer that you have added to the NSModalPanelRunLoopMode mode of the default NSRunLoop.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

activateContextHelpMode:

Places the receiver in context-sensitive help mode.

- (void)activateContextHelpMode:(id)sender
Parameters
sender

The object that sent the command.

Discussion

In this mode, the cursor becomes a question mark, and help appears for any user interface item the user clicks.

Most applications don’t use this method. Instead, applications enter context-sensitive mode when the user presses the Help key. Applications exit context-sensitive help mode upon the first event after a help window is displayed.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSHelpManager.h

activateIgnoringOtherApps:

Makes the receiver the active application.

- (void)activateIgnoringOtherApps:(BOOL)flag
Parameters
flag

If NO, the application is activated only if no other application is currently active. If YES, the application activates regardless.

Discussion

The flag parameter is normally set to NO. When the Finder launches an application, using a value of NO for flag allows the application to become active if the user waits for it to launch, but the application remains unobtrusive if the user activates another application. Regardless of the setting of flag, there may be a time lag before the application activates—you should not assume the application will be active immediately after sending this message.

You rarely need to invoke this method. Under most circumstances, the Application Kit takes care of proper activation. However, you might find this method useful if you implement your own methods for inter-application communication.

You don’t need to send this message to make one of the application’s NSWindows key. When you send a makeKeyWindow message to an NSWindow object, you ensure that it is the key window when the application is active.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

activationPolicy

Returns the application’s activation policy.

- (NSApplicationActivationPolicy)activationPolicy
Return Value

The application’s current activation policy.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

addWindowsItem:title:filename:

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

- (void)addWindowsItem:(NSWindow *)aWindow title:(NSString *)aString filename:(BOOL)isFilename
Parameters
aWindow

The window being added to the menu. If this window object already exists in the Window menu, this method has no effect.

aString

The string to display for the window’s menu item. How the string is interpreted is dependent on the value in the isFilename parameter.

isFilename

If NO, aString appears literally in the menu; otherwise, aString is assumed to be a converted pathname with the name of the file preceding the path (the way the NSWindow method setTitleWithRepresentedFilename: shows a title)

Discussion

You rarely need to invoke this method directly because Cocoa places an item in the Window menu automatically whenever you set the title of an NSWindow object.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

applicationIconImage

Returns the image used for the receiver’s icon.

- (NSImage *)applicationIconImage
Return Value

An image containing the application’s icon.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

arrangeInFront:

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

- (void)arrangeInFront:(id)sender
Parameters
sender

The object that sent the command.

Discussion

Windows associated with the application but not listed in the Window menu are not ordered to the front.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

beginModalSessionForWindow:

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

- (NSModalSession)beginModalSessionForWindow:(NSWindow *)aWindow
Parameters
aWindow

The window for the session.

Return Value

The NSModalSession structure that represents the session.

Discussion

In a modal session, the application receives mouse events only if they occur in aWindow. The window is made key, and if not already visible is placed onscreen using the NSWindow method center.

The beginModalSessionForWindow: method only sets up the modal session. To actually run the session, use runModalSession:. beginModalSessionForWindow: should be balanced by endModalSession:. Make sure these two messages are sent within the same exception-handling scope. That is, if you send beginModalSessionForWindow: inside an NS_DURING construct, you must send endModalSession: before NS_ENDHANDLER.

If an exception is raised, beginModalSessionForWindow: arranges for proper cleanup. Do not use NS_DURING constructs to send an endModalSession: message in the event of an exception.

A loop using these methods is similar to a modal event loop run with runModalForWindow:, except the application can continue processing between method invocations.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

cancelUserAttentionRequest:

Cancels a previous user attention request.

- (void)cancelUserAttentionRequest:(NSInteger)request
Parameters
request

The request identifier returned by the requestUserAttention: method.

Discussion

A request is also canceled automatically by user activation of the application.

Availability
  • Available in OS X v10.1 and later.
Declared In
NSApplication.h

changeWindowsItem:title:filename:

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

- (void)changeWindowsItem:(NSWindow *)aWindow title:(NSString *)aString filename:(BOOL)isFilename
Parameters
aWindow

The window whose title you want to change in the Window menu. If aWindow is not in the Window menu, this method adds it.

aString

The string to display for the window’s menu item. How the string is interpreted is dependent on the value in the isFilename parameter.

isFilename

If NO, aString appears literally in the menu; otherwise, aString is assumed to be a converted pathname with the name of the file preceding the path (the way the NSWindow method setTitleWithRepresentedFilename: shows a title)

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

completeStateRestoration

Completes the extended state restoration.

- (void)completeStateRestoration
Discussion

This method informs the application that the extended state restoration is completed for the balancing .

If a window has some state that may take a long time to restore, such as a web page, you may use this method and methods to completeStateRestoration to extend the period of this crash protection beyond the default.

You call extendStateRestoration within your implementation of restoreWindowWithIdentifier:state:completionHandler:. You would then call completeStateRestoration some time after the window is fully restored. If the app crashes in the interim, then it may offer to discard restorable state on the next launch.

The extendStateRestoration and completeStateRestoration method act as a counter. Each call to extendStateRestorationincrements the counter, and must be matched with a corresponding call to completeStateRestoration which decrements it. When the counter reaches zero, the app is considered to have been fully restored, and any further calls are silently ignored.

This method is thread safe.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

context

Returns the receiver’s display context.

- (NSGraphicsContext *)context
Return Value

The current display context for the application.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

currentEvent

Returns the current event, the last event the receiver retrieved from the event queue.

- (NSEvent *)currentEvent
Return Value

The last event object retrieved by the application.

Discussion

NSApp receives events and forwards them to the affected NSWindow objects, which then distribute them to the objects in its view hierarchy.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

currentSystemPresentationOptions

Returns the set of application presentation options that are currently in effect for the system.

- (NSApplicationPresentationOptions)currentSystemPresentationOptions
Return Value

The presentation options. The constants are listed in NSApplicationPresentationOptions and can combined using a C bitwise OR operator.

Discussion

These are the presentation options that have been put into effect by the currently active application.

This method is key-value observable.

A client that observes currentSystemPresentationOptions will receive notifications when

  • The client is the active application, and makes a change itself using either setPresentationOptions: or SetSystemUIMode.

  • Another application is active, and makes presentation changes of its own.

  • Another application becomes active and causes the active set of presentation options to change.

Key-value observing notifications are not sent when one of the above conditions occur, but has the same set of presentation options as the previously active application.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

deactivate

Deactivates the receiver.

- (void)deactivate
Discussion

Normally, you shouldn’t invoke this method—the Application Kit is responsible for proper deactivation.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

delegate

Returns the receiver’s delegate.

- (id<NSApplicationDelegate>)delegate
Return Value

The application delegate object.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

disableRelaunchOnLogin

Disables relaunching the application on login.

- (void)disableRelaunchOnLogin
Discussion

Invoking this method will prevent the application from relaunching when the user next logs in to their account.

If your application should not be relaunched because it launches via some other mechanism (e.g. launchd), then the recommended usage is to call this method once, and never pair it with an enableRelaunchOnLogin method.

If your application should not be relaunched because it triggers a restart, for example an installer, then the recommended usage is to invoke this method immediately before you attempt to trigger a restart, and enableRelaunchOnLogin immediately after. This is because the user may cancel restarting; if the user later restarts for another reason, then your application should be brought back.

This methods is thread safe.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSApplication.h

discardEventsMatchingMask:beforeEvent:

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

- (void)discardEventsMatchingMask:(NSUInteger)mask beforeEvent:(NSEvent *)lastEvent
Parameters
mask

Contains one or more flags indicating the types of events to discard. The constants section of the NSEvent class defines the constants you can add together to create this mask. The discussion section also lists some of the constants that are typically used.

lastEvent

A marker event that you use to indicate which events should be discarded. Events that occurred before this event are discarded but those that occurred after it are not.

Discussion

Use this method to ignore any events that occurred before a specific event. For example, suppose your application has a tracking loop that you exit when the user releases the mouse button. You could use this method, specifying NSAnyEventMask as the mask argument and the ending mouse-up event as the lastEvent argument, to discard all events that occurred while you were tracking mouse movements in your loop. Passing the mouse-up event as lastEvent ensures that any events that might have occurred after the mouse-up event (that is, that appear in the queue after the mouse-up event) are not discarded.

For the mask parameter, you can add together event type constants such as the following:

This method can also be called in subthreads. Events posted in subthreads bubble up in the main thread event queue.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

dockTile

Returns the application’s Dock tile.

- (NSDockTile *)dockTile
Return Value

The application’s Dock tile.

Availability
  • Available in OS X v10.5 and later.
Related Sample Code
Declared In
NSApplication.h

enabledRemoteNotificationTypes

Returns the types of notifications the application accepts.

- (NSRemoteNotificationType)enabledRemoteNotificationTypes
Return Value

A bit mask whose values indicate the types of notifications the user has requested for the application. See “NSRemoteNotificationType” for valid bit-mask values.

Discussion

The values in the returned bit mask indicate the types of notifications currently enabled for the application. These types are set when the application calls the registerForRemoteNotificationTypes: method to register itself with Apple Push Notification Service. This method returns those initial values. Mac OS X does not display or play notification types specified in the notification payload that are not one of the enabled types.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSApplication.h

enableRelaunchOnLogin

Enables relaunching the application on login.

- (void)enableRelaunchOnLogin
Discussion

Invoking this method will cause the application to relaunch when the user next logs in to their account.

This methods is thread safe.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSApplication.h

endModalSession:

Finishes a modal session.

- (void)endModalSession:(NSModalSession)session
Parameters
session

A modal session structure returned by a previous invocation of beginModalSessionForWindow:.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

extendStateRestoration

Allows an application to extend its state restoration period.

- (void)extendStateRestoration
Discussion

This method allows an application to extend the state restoration period beyond the usual. For example, the app crashes before state restoration is complete, then it may offer to discard restorable state on the next launch.

If a window has some state that may take a long time to restore, such as a web page, you may use this method and methods to completeStateRestoration to extend the period of this crash protection beyond the default.

You call extendStateRestoration within your implementation of restoreWindowWithIdentifier:state:completionHandler:. You would then call completeStateRestoration some time after the window is fully restored. If the app crashes in the interim, then it may offer to discard restorable state on the next launch.

The extendStateRestoration and completeStateRestoration method act as a counter. Each call to extendStateRestoration increments the counter, and must be matched with a corresponding call to completeStateRestoration which decrements it. When the counter reaches zero, the app is considered to have been fully restored, and any further calls are silently ignored.

This method is thread safe.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

finishLaunching

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

- (void)finishLaunching
Discussion

The run method invokes this method before it starts the event loop. When this method begins, it posts an NSApplicationWillFinishLaunchingNotification to the default notification center. If you override finishLaunching, the subclass method should invoke the superclass method.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

helpMenu

Returns the help menu used by the application.

- (NSMenu *)helpMenu
Return Value

Returns the application’s help menu.

Discussion

If helpMenu is nil, the system will append the help to an appropriate menu and will not return a reference to that menu when this method is called.,

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

hide:

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

- (void)hide:(id)sender
Parameters
sender

The object that sent the command.

Discussion

This method is usually invoked when the user chooses Hide in the application’s main menu. When this method begins, it posts an NSApplicationWillHideNotification to the default notification center. When it completes successfully, it posts an NSApplicationDidHideNotification.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

hideOtherApplications:

Hides all applications, except the receiver.

- (void)hideOtherApplications:(id)sender
Parameters
sender

The object that sent this message.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

isActive

Returns a Boolean value indicating whether this is the active application.

- (BOOL)isActive
Return Value

YES if this is the active application; NO otherwise.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

isFullKeyboardAccessEnabled

Returns that status of Full Keyboard Access set in the Keyboard preference pane.

- (BOOL)isFullKeyboardAccessEnabled
Return Value

YES if Full Keyboard Access is enabled, otherwise NO.

Discussion

You may use this status to implement your own key loop or to implement in-control tabbing behavior similar to NSTableView. Because of the nature of the preference storage, you will not be notified of changes to the key if you attempt to observe it via key-value observing; however, calling this method is fairly inexpensive, so you should always call it when you need the underlying value instead of caching it.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

isHidden

Returns a Boolean value indicating whether the receiver is hidden.

- (BOOL)isHidden
Return Value

YES if the receiver is hidden, NO otherwise.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

isRunning

Returns a Boolean value indicating whether the main event loop is running.

- (BOOL)isRunning
Return Value

YES if the main event loop is running; NO otherwise.

Discussion

NO means the stop: method was invoked.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

keyWindow

Returns the window that currently receives keyboard events.

- (NSWindow *)keyWindow
Return Value

The window object currently receiving keyboard events or nil if there is no key window.

Discussion

This method might return nil if the application’s nib file hasn’t finished loading yet or if the receiver is not active.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

mainMenu

Returns the receiver’s main menu.

- (NSMenu *)mainMenu
Return Value

The menu object representing the application’s menu bar.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

mainWindow

Returns the main window.

- (NSWindow *)mainWindow
Return Value

The application’s main window or nil if there is no main window.

Discussion

This method might return nil if the application’s nib file hasn’t finished loading, if the receiver is not active, or if the application is hidden.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

makeWindowsPerform:inOrder:

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

- (NSWindow *)makeWindowsPerform:(SEL)aSelector inOrder:(BOOL)flag
Parameters
aSelector

The selector to perform on each window. This method must not take any arguments and must return a value whose type that can be compared to nil.

flag

If YES, the aSelector message is sent to each of the window server’s onscreen windows, going in z-order, until one returns a non-nil value. A minimized window is not considered to be onscreen for this check. If NO, the message is sent to all windows in NSApp’s window list, regardless of whether or not they are onscreen. This order is unspecified.

Return Value

The window that returned a non-nil value or nil if all windows returned nil from aSelector.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

miniaturizeAll:

Miniaturizes all the receiver’s windows.

- (void)miniaturizeAll:(id)sender
Parameters
sender

The object that sent the command.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

modalWindow

Returns the modal window that the receiver is displaying.

- (NSWindow *)modalWindow
Return Value

The modal window being displayed or nil if no modal window is being displayed.

Discussion

This method returns the current standalone modal window. It does not return sheets that are attached to other windows. If you need to retrieve a sheet window, use the attachedSheet method of NSWindow.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

nextEventMatchingMask:untilDate:inMode:dequeue:

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

- (NSEvent *)nextEventMatchingMask:(NSUInteger)mask untilDate:(NSDate *)expiration inMode:(NSString *)mode dequeue:(BOOL)flag
Parameters
mask

Contains one or more flags indicating the types of events to return. The constants section of the NSEvent class defines the constants you can add together to create this mask. The discardEventsMatchingMask:beforeEvent: method also lists several of these constants.

expiration

The expiration date for the current event request. Specifying nil for this parameter is equivalent to returning a date object using the distantPast method.

mode

The run loop mode in which to run while looking for events. The mode you specify also determines which timers and run-loop observers may fire while the application waits for the event.

flag

Specify YES if you want the event removed from the queue.

Return Value

The event object whose type matches one of the event types specified by the mask parameter.

Discussion

You can use this method to short circuit normal event dispatching and get your own events. For example, you may want to do this in response to a mouse-down event in order to track the mouse while its button is down. (In such an example, you would pass the appropriate event types for mouse-dragged and mouse-up events to the mask parameter and specify the NSEventTrackingRunLoopMode run loop mode.) Events that do not match one of the specified event types are left in the queue.

You can specify one of the run loop modes defined by the Application Kit or a custom run loop mode used specifically by your application. Application Kit defines the following run-loop modes:

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

occlusionState

Returns the occlusion state of the application

- (NSApplicationOcclusionState)occlusionState
Return Value

The occlusion state of the application. See NSApplicationOcclusionState for possible values.

Availability
  • Available in OS X v10.9 and later.
Declared In
NSApplication.h

orderedDocuments

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

- (NSArray *)orderedDocuments
Return Value

An array of NSDocument objects, where the position of a document is based on the front-to-back ordering of its associated window.

Discussion

This method is called during script command evaluation—for example, while finding the document in the script statement the third rectangle in the first document. For information on how your application can return its own array of ordered documents, see application:delegateHandlesKey:.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplicationScripting.h

orderedWindows

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

- (NSArray *)orderedWindows
Return Value

An array of NSWindow objects, where the position of each window in the array corresponds to the front-to-back ordering of the windows on the screen.

Discussion

Only windows that are typically scriptable are included in the returned array. For example, panels are not included.

This method is called during script command evaluation—for example, while finding the window in the script statement close the second window. For information on how your application can return its own array of ordered windows, see application:delegateHandlesKey:.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplicationScripting.h

orderFrontCharacterPalette:

Opens the character palette.

- (void)orderFrontCharacterPalette:(id)sender
Parameters
sender

The object that sent the command.

Availability
  • Available in OS X v10.3 and later.
Declared In
NSApplication.h

orderFrontColorPanel:

Brings up the color panel, an instance of NSColorPanel.

- (void)orderFrontColorPanel:(id)sender
Parameters
sender

The object that sent the command.

Discussion

If the NSColorPanel object does not exist yet, this method creates one. This method is typically invoked when the user chooses Colors from a menu.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSColorPanel.h

orderFrontStandardAboutPanel:

Displays a standard About window.

- (void)orderFrontStandardAboutPanel:(id)sender
Parameters
sender

The object that sent the command.

Discussion

This method calls orderFrontStandardAboutPanelWithOptions: with a nil argument. See orderFrontStandardAboutPanelWithOptions: for a description of what’s displayed.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

orderFrontStandardAboutPanelWithOptions:

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

- (void)orderFrontStandardAboutPanelWithOptions:(NSDictionary *)optionsDictionary
Parameters
optionsDictionary

A dictionary whose keys define the contents of the About window. See the discussion for a description of the available keys.

Discussion

The following strings are keys that can occur in optionsDictionary:

  • @"Credits": An NSAttributedString displayed in the info area of the panel. If not specified, this method then looks for a file named “Credits.html”, “Credits.rtf”, and “Credits.rtfd”, in that order, in the bundle returned by the NSBundle class method mainBundle. The first file found is used. If none is found, the info area is left blank.

  • @"ApplicationName": An NSString object displayed as the application’s name. If not specified, this method then uses the value of CFBundleName (localizable). If neither is found, this method uses [[NSProcessInfo processInfo] processName].

  • @"ApplicationIcon": An NSImage object displayed as the application’s icon. If not specified, this method then looks for an image named “NSApplicationIcon”, using [NSImage imageNamed:@"NSApplicationIcon"]. If neither is available, this method uses the generic application icon.

  • @"Version": An NSString object with the build version number of the application (“58.4”), displayed as “(v58.4)”. If not specified, obtain from the CFBundleVersion key in infoDictionary; if not specified, leave blank (the “(v)” is not displayed).

  • @"Copyright": An NSString object with a line of copyright information. If not specified, this method then looks for the value of NSHumanReadableCopyright in the localized version infoDictionary. If neither is available, this method leaves the space blank.

  • @"ApplicationVersion": An NSString object with the application version (“Mac OS X”, “3”, “WebObjects 4.5”, “AppleWorks 6”,...). If not specified, obtain from the CFBundleShortVersionString key in infoDictionary. If neither is available, the build version, if available, is printed alone, as “Version x.x”.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

postEvent:atStart:

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

- (void)postEvent:(NSEvent *)anEvent atStart:(BOOL)flag
Parameters
anEvent

The event object to post to the queue.

flag

Specify YES to add the event to the front of the queue; otherwise, specify NO to add the event to the back of the queue.

Discussion

This method can also be called in subthreads. Events posted in subthreads bubble up in the main thread event queue.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

presentationOptions

Returns the presentation options that should be in effect for the system when this application is active.

- (NSApplicationPresentationOptions)presentationOptions
Return Value

The application’s presentation options. The constants are listed in NSApplicationPresentationOptions and they combined using a C bitwise OR operator.

Discussion

This method is key-value observable.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

preventWindowOrdering

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

- (void)preventWindowOrdering
Discussion

This method is only useful for mouse-down events when you want to prevent the window that receives the event from being ordered to the front.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

registerForRemoteNotificationTypes:

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

- (void)registerForRemoteNotificationTypes:(NSRemoteNotificationType)types
Parameters
types

A bit mask specifying the types of notifications the application accepts. See “NSRemoteNotificationType” for valid bit-mask values.

Discussion

When you send this message, the device initiates the registration process with Apple Push Notification Service. If it succeeds, the application delegate receives a device token in the application:didRegisterForRemoteNotificationsWithDeviceToken: method; if registration doesn’t succeed, the delegate is informed via the application:didFailToRegisterForRemoteNotificationsWithError: method. If the application delegate receives a device token, it should connect with its provider and pass it the token.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSApplication.h

registerServicesMenuSendTypes:returnTypes:

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

- (void)registerServicesMenuSendTypes:(NSArray *)sendTypes returnTypes:(NSArray *)returnTypes
Parameters
sendTypes

An array of NSString objects, each of which corresponds to a particular pasteboard type that the application can send.

returnTypes

An array of NSString objects, each of which corresponds to a particular pasteboard type that the application can receive.

Discussion

If the receiver has a Services menu, a menu item is added for each service provider that can accept one of the specified sendTypes or return one of the specified returnTypes. You should typically invoke this method at application startup time or when an object that can use services is created. You can invoke it more than once—its purpose is to ensure there is a menu item for every service the application can use. The event-handling mechanism will dynamically enable the individual items to indicate which services are currently appropriate. All the NSResponder objects in your application (typically NSView objects) should register every possible type they can send and receive by sending this message to NSApp.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

registerUserInterfaceItemSearchHandler:

Register an an object that provides help data to your application.

- (void)registerUserInterfaceItemSearchHandler:(id<NSUserInterfaceItemSearching>)handler
Parameters
handler

The class instance that conforms to NSUserInterfaceItemSearching and provides help content.

Discussion

You can register as many search handlers as you like. If you register the same instance more than once the subsequent registrations are ignored.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSUserInterfaceItemSearching.h

removeWindowsItem:

Removes the Window menu item for a given window.

- (void)removeWindowsItem:(NSWindow *)aWindow
Parameters
aWindow

The window whose menu item is to be removed.

Discussion

This method doesn’t prevent the item from being automatically added again. Use the setExcludedFromWindowsMenu: method of NSWindow if you want the item to remain excluded from the Window menu.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

replyToApplicationShouldTerminate:

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

- (void)replyToApplicationShouldTerminate:(BOOL)shouldTerminate
Parameters
shouldTerminate

Specify YES if you want the application to terminate; otherwise, specify NO.

Discussion

If your application delegate returns NSTerminateLater from its applicationShouldTerminate: method, your code must subsequently call this method to let the NSApplication object know whether it can actually terminate itself.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

replyToOpenOrPrint:

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

- (void)replyToOpenOrPrint:(NSApplicationDelegateReply)reply
Parameters
reply

The error that occurred. For a list of possible values, see “Constants.”

Discussion

Delegates should invoke this method if an error is encountered in the application:openFiles: or application:printFiles:withSettings:showPrintPanels: delegate methods.

Availability
  • Available in OS X v10.3 and later.
Declared In
NSApplication.h

reportException:

Logs a given exception by calling NSLog().

- (void)reportException:(NSException *)anException
Parameters
anException

The exception whose contents you want to write to the log file.

Discussion

This method does not raise anException. Use it inside of an exception handler to record that the exception occurred.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

requestUserAttention:

Starts a user attention request.

- (NSInteger)requestUserAttention:(NSRequestUserAttentionType)requestType
Parameters
requestType

The severity of the request. For a list of possible values, see “Constants.”

Return Value

The identifier for the request. You can use this value to cancel the request later using the cancelUserAttentionRequest: method.

Discussion

Activating the application cancels the user attention request. A spoken notification will occur if spoken notifications are enabled. Sending requestUserAttention: to an application that is already active has no effect.

If the inactive application presents a modal panel, this method will be invoked with NSCriticalRequest automatically. The modal panel is not brought to the front for an inactive application.

Availability
  • Available in OS X v10.1 and later.
Declared In
NSApplication.h

restoreWindowWithIdentifier:state:completionHandler:

Invoked to request that a window be restored.

- (BOOL)restoreWindowWithIdentifier:(NSString *)identifier state:(NSCoder *)state completionHandler:(void (^)(NSWindow *, NSError *))completionHandler
Parameters
identifier

The unique interface item identifier string that was previously associated with the window. Use this string to determine which window to create.

state

A coder object containing the window state information. This coder object contains the combined restorable state of the window, which can include the state of the window, its delegate, window controller, and document object. You can use this state to determine which window to create.

completionHandler

A Block object to execute with the results of creating the window. You must execute this block at some point but may do so after the method returns if needed. This block takes the following parameters:

  • The window that was created or nil if the window could not be created.

  • An error object if the window was not recognized or could not be created for whatever reason; otherwise, specify nil. In OS X v10.7, the error parameter is ignored.

Return Value

YES if the window was restored; otherwise NO.

Discussion

If the receiver knows how to restore the identified window, it should invoke the completion handler with the window, possibly creating it. It is acceptable to use a pre-existing window, though you should not pass the same window to more than one completion handler. If the receiver cannot restore the identified window (for example, the window referenced a document that has been deleted), it should invoke the completion handler with a nil window.

The receiver is application is passed the identifier of the window, which allows it to quickly check for known windows. For example, you might give your preferences window an identifier of "preferences" in the nib, and then check for that identifier in your implementation. The receiver is also passed the NSCoder instance containing the combined restorable state of the window, its delegate, the window controller, and any document. The receiver may decode information previously stored in the coder to determine what window to restore.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSWindowRestoration.h

run

Starts the main event loop.

- (void)run
Discussion

The loop continues until a stop: or terminate: message is received. Upon each iteration through the loop, the next available event from the window server is stored and then dispatched by sending it to NSApp using sendEvent:.

After creating the NSApplication object, the main function should load your application’s main nib file and then start the event loop by sending the NSApplication object a run message. If you create an Cocoa application project in Xcode, this main function is implemented for you.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

runModalForWindow:

Starts a modal event loop for a given window.

- (NSInteger)runModalForWindow:(NSWindow *)aWindow
Parameters
aWindow

The window to be displayed modally. If it is not already visible, the window is centered on the screen using the value in its centermethod and made visible and key. If it is already visible, it is simply made key.

Return Value

An integer indicating the reason that this method returned. See NSModalResponse possible return values.

Discussion

This method runs a modal event loop for the specified window synchronously. It displays the specified window, makes it key, starts the run loop, and processes events for that window. (You do not need to show the window yourself.) While the application is in that loop, it does not respond to any other events (including mouse, keyboard, or window-close events) unless they are associated with the window. It also does not perform any tasks (such as firing timers) that are not associated with the modal run loop. In other words, this method consumes only enough CPU time to process events and dispatch them to the action methods associated with the modal window.

You can exit the modal loop by calling the stopModal, stopModalWithCode:, or abortModal methods from your modal window code. If you use the stopModalWithCode: method to stop the modal event loop, this method returns the argument passed to stopModalWithCode:. If you use stopModal instead, this method returns the constant NSModalResponseStop. If you use abortModal, this method returns the constant NSModalResponseAbort.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

runModalSession:

Runs a given modal session, as defined in a previous invocation of beginModalSessionForWindow:.

- (NSInteger)runModalSession:(NSModalSession)session
Parameters
session

The modal session structure returned by the beginModalSessionForWindow: method for the window to be displayed.

Return Value

An integer indicating the reason that this method returned. See the discussion for a description of possible return values.

Discussion

A loop that uses this method is similar in some ways to a modal event loop run with runModalForWindow:, except with this method your code can do some additional work between method invocations. When you invoke this method, events for the NSWindow object of this session are dispatched as normal. This method returns when there are no more events. You must invoke this method frequently enough in your loop that the window remains responsive to events. However, you should not invoke this method in a tight loop because it returns immediately if there are no events, and consequently you could end up polling for events rather than blocking.

Typically, you use this method in situations where you want to do some additional processing on the current thread while the modal loop runs. For example, while processing a large data set, you might want to use a modal dialog to display progress and give the user a chance to cancel the operation. If you want to display a modal dialog and do not need to do any additional work in parallel, use runModalForWindow: instead. When there are no pending events, that method waits idly instead of consuming CPU time.

The following code shows a sample loop you can use in your code:

NSModalSession session = [NSApp beginModalSessionForWindow:theWindow];
for (;;) {
    if ([NSApp runModalSession:session] != NSModalResponseContinue)
        break;
    [self doSomeWork];
}
[NSApp endModalSession:session];

If the modal session was not stopped, this method returns NSModalResponseContinue. At this point, your application can do some work before the next invocation of runModalSession: (as indicated in the example’s doSomeWork call). If stopModal was invoked as the result of event processing, runModalSession: returns NSModalResponseStop. If stopModalWithCode: was invoked, this method returns the value passed to stopModalWithCode:. If abortModal was invoked, this method returns NSModalResponseAbort.

The window is placed on the screen and made key as a result of the runModalSession: message. Do not send a separate makeKeyAndOrderFront: message.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

runPageLayout:

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

- (void)runPageLayout:(id)sender
Parameters
sender

The object that sent the command.

Discussion

If the NSPageLayout instance does not exist, this method creates one. This method is typically invoked when the user chooses Page Setup from the application’s File menu.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSPageLayout.h

searchString:inUserInterfaceItemString:searchRange:foundRange:

Searches for the string in the user interface.

- (BOOL)searchString:(NSString *)searchString inUserInterfaceItemString:(NSString *)stringToSearch searchRange:(NSRange)searchRange foundRange:(NSRange *)foundRange
Parameters
searchString

The search string.

stringToSearch

The string to search.

searchRange

The subrange of the stringToSearch to restrict the search to.

foundRange

Returns, by-reference, the range of the searchString within stringToSearch.

Return Value

YES if the searchString is matched, otherwise NO.

Discussion

The search uses the default matching rules for Spotlight for Help.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSUserInterfaceItemSearching.h

sendAction:to:from:

Sends the given action message to the given target.

- (BOOL)sendAction:(SEL)anAction to:(id)aTarget from:(id)sender
Parameters
anAction

The action message you want to send.

aTarget

The target object that defines the specified action message.

sender

The object to pass for the action message’s parameter.

Return Value

YES if the action was successfully sent; otherwise NO. This method also returns NO if anAction is nil.

Discussion

If aTarget is nil, sharedApplication looks for an object that can respond to the message—that is, an object that implements a method matching anAction. It begins with the first responder of the key window. If the first responder can’t respond, it tries the first responder’s next responder and continues following next responder links up the responder chain. If none of the objects in the key window’s responder chain can handle the message, sharedApplication attempts to send the message to the key window’s delegate.

If the delegate doesn’t respond and the main window is different from the key window, sharedApplication begins again with the first responder in the main window. If objects in the main window can’t respond, sharedApplication attempts to send the message to the main window’s delegate. If still no object has responded, sharedApplication tries to handle the message itself. If sharedApplication can’t respond, it attempts to send the message to its own delegate.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

sendEvent:

Dispatches an event to other objects.

- (void)sendEvent:(NSEvent *)anEvent
Parameters
anEvent

The event object to dispatch.

Discussion

You rarely invoke sendEvent: directly, although you might want to override this method to perform some action on every event. sendEvent: messages are sent from the main event loop (the run method). sendEvent: is the method that dispatches events to the appropriate responders—NSApp handles application events, the NSWindow object indicated in the event record handles window-related events, and mouse and key events are forwarded to the appropriate NSWindow object for further dispatching.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

servicesMenu

Returns the Services menu.

- (NSMenu *)servicesMenu
Return Value

The Services menu or nil if no Services menu has been created

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

servicesProvider

Returns the object that provides the services the receiver advertises in the Services menu of other applications.

- (id)servicesProvider
Return Value

The application’s service provider object.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

setActivationPolicy:

Attempts to modify the application's activation policy.

- (BOOL)setActivationPolicy:(NSApplicationActivationPolicy)activationPolicy
Parameters
activationPolicy

The desired activation policy.

Return Value

YES if the policy switch was successful, otherwise NO.

Discussion

Currently, NSApplicationActivationPolicyNone and NSApplicationActivationPolicyAccessory may be changed to NSApplicationActivationPolicyRegular, but other modifications are not supported.Needs links to running application

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

setApplicationIconImage:

Sets the receiver’s icon to the specified image.

- (void)setApplicationIconImage:(NSImage *)anImage
Parameters
anImage

The image to use as the new application icon.

Discussion

This method sets the icon in the dock application tile. This method scales the image as necessary so that it fits in the dock tile. You can use this method to change your application icon while running. To restore your application’s original icon, you pass nil to this method.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

setDelegate:

Makes the given object the receiver’s delegate.

- (void)setDelegate:(id<NSApplicationDelegate>)anObject
Parameters
anObject

The application delegate object.

Discussion

The messages a delegate can expect to receive are listed at the end of this specification. The delegate doesn’t need to implement all the methods.

Availability
  • Available in OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSApplication.h

setHelpMenu:

Sets the application’s help menu.

- (void)setHelpMenu:(NSMenu *)helpMenu
Parameters
helpMenu

The menu to use as the application’s help menu.

Discussion

If helpMenu is a non-nil menu it is set as the Help menu, and Spotlight for Help will be installed in it. If helpMenu is nil, AppKit will install Spotlight for Help into a menu of its choosing, and that menu is not returned from helpMenu.

If you wish to completely suppress Spotlight for Help, you can set a menu that does not appear in the menu bar.

NSApplication maintains a strong reference to its Help menu.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

setMainMenu:

Makes the given menu the receiver’s main menu.

- (void)setMainMenu:(NSMenu *)aMenu
Parameters
aMenu

The new menu bar for the application.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

setPresentationOptions:

Sets the application presentation options to use when this application is active.

- (void)setPresentationOptions:(NSApplicationPresentationOptions)newOptions
Parameters
newOptions

The presentation options. The possible constants, and combination restrictions, are listed in NSApplicationPresentationOptions and they combined using a C bitwise OR operator.

Discussion

Only certain combinations of NSApplicationPresentationOptions flags are supported. When given an invalid combination of option flags this method raises an exception NSInvalidArgumentException exception..

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

setServicesMenu:

Makes a given menu the receiver’s Services menu.

- (void)setServicesMenu:(NSMenu *)aMenu
Parameters
aMenu

The new Services menu.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

setServicesProvider:

Registers a given object as the service provider.

- (void)setServicesProvider:(id)aProvider
Parameters
aProvider

The new service provider object.

Discussion

The service provider is an object that performs all services the application provides to other applications. When another application requests a service from the receiver, it sends the service request to aProvider. Service requests can arrive immediately after the service provider is set, so invoke this method only when your application is ready to receive requests.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

setWindowsMenu:

Makes the given menu the receiver’s Window menu.

- (void)setWindowsMenu:(NSMenu *)aMenu
Parameters
aMenu

The new Window menu for the application.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

setWindowsNeedUpdate:

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

- (void)setWindowsNeedUpdate:(BOOL)flag
Parameters
flag

If YES, the receiver’s windows are updated after an event is processed.

Discussion

This method is especially useful for making sure menus are updated to reflect changes not initiated by user actions, such as messages received from remote objects.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

showHelp:

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 application’s help book.

- (void)showHelp:(id)sender
Parameters
sender

The object that sent the command.

Discussion

For information on how to set up your project to take advantage of having Help Viewer display your help book, see “Specifying the Comprehensive Help File”.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSHelpManager.h

stop:

Stops the main event loop.

- (void)stop:(id)sender
Parameters
sender

The object that sent this message.

Discussion

This method notifies the application that you want to exit the current run loop as soon as it finishes processing the current NSEvent object. This method does not forcibly exit the current run loop. Instead it sets a flag that the application checks only after it finishes dispatching an actual event object. For example, you could call this method from an action method responding to a button click or from one of the many methods defined by the NSResponder class. However, calling this method from a timer or run-loop observer routine would not stop the run loop because they do not result in the posting of an NSEvent object.

If you call this method from an event handler running in your main run loop, the application object exits out of the run method, thereby returning control to the main() function. If you call this method from within a modal event loop, it will exit the modal loop instead of the main event loop.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

stopModal

Stops a modal event loop.

- (void)stopModal
Discussion

This method should always be paired with a previous invocation of runModalForWindow: or beginModalSessionForWindow:. When runModalForWindow: is stopped with this method, it returns NSModalResponseStop. This method stops the loop only if it’s executed by code responding to an event. If you need to stop a runModalForWindow: loop outside of one of its event callbacks (for example, a method repeatedly invoked by an NSTimer object or a method running in a different thread), use the abortModal method.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

stopModalWithCode:

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

- (void)stopModalWithCode:(NSInteger)returnCode
Parameters
returnCode

The result code you want returned from the runModalForWindow: or runModalSession: method. The meaning of this result code is up to you.

Discussion

This method should always be paired with a previous invocation of runModalForWindow: or beginModalSessionForWindow:. When runModalForWindow: is stopped with this method, it returns the given returnCode. This method stops the loop only if it’s executed by code responding to an event. If you need to stop a runModalForWindow: loop outside of one of its event callbacks (for example, a method repeatedly invoked by an NSTimer object or a method running in a different thread), use the abortModal method.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

targetForAction:

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

- (id)targetForAction:(SEL)aSelector
Parameters
aSelector

The desired action message.

Return Value

The object that would receive the specified action message or nil if no target object would receive the message. This method also returns nil if aSelector is nil.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

targetForAction:to:from:

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

- (id)targetForAction:(SEL)anAction to:(id)aTarget from:(id)sender
Parameters
anAction

The desired action message. May be nil, in which case this method will return nil.

aTarget

The target object to check. Specify nil if you want to search the responder chain starting with the current first responder.

sender

The potential sender for the action message.

Return Value

The object that can accept the specified action message or nil if no target object can receive the message from the specified sender. Returns nil if anAction is nil.

Discussion

The system looks for an object that implements a method matching anAction.

If aTarget is specified, the system verifies that it is a valid target for the provided action and sender, returning aTarget if valid, nil otherwise.

If the provided target is nil, the search begins with the first responder of the key window. The system follows the responder chain looking for targets. If no object capable of handling the message is found in the responder chain, returns nil.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

terminate:

Terminates the receiver.

- (void)terminate:(id)sender
Parameters
sender

Typically, this parameter contains the object that initiated the termination request.

Discussion

This method is typically invoked when the user chooses Quit or Exit from the application’s menu.

When invoked, this method performs several steps to process the termination request. First, it asks the application’s document controller (if one exists) to save any unsaved changes in its documents. During this process, the document controller can cancel termination in response to input from the user. If the document controller does not cancel the operation, this method then calls the delegate’s applicationShouldTerminate: method. If applicationShouldTerminate: returns NSTerminateCancel, the termination process is aborted and control is handed back to the main event loop. If the method returns NSTerminateLater, the application runs its run loop in the NSModalPanelRunLoopMode mode until the replyToApplicationShouldTerminate: method is called with the value YES or NO. If the applicationShouldTerminate: method returns NSTerminateNow, this method posts a NSApplicationWillTerminateNotification notification to the default notification center.

Do not bother to put final cleanup code in your application’s main() function—it will never be executed. If cleanup is necessary, perform that cleanup in the delegate’s applicationWillTerminate: method.

Availability
  • Available in OS X v10.0 and later.
Related Sample Code
Declared In
NSApplication.h

tryToPerform:with:

Dispatches an action message to the specified target.

- (BOOL)tryToPerform:(SEL)aSelector with:(id)anObject
Parameters
aSelector

The action message you want to dispatch.

anObject

The target object that defines the specified selector.

Return Value

YES if either the receiver or its delegate can accept the specified selector; otherwise, NO. This method also returns NO if aSelector is nil.

Discussion

The receiver tries to perform the method aSelector using its inherited tryToPerform:with: method of NSResponder. If the receiver doesn’t perform aSelector, the delegate is given the opportunity to perform it using its inherited performSelector:withObject: method of NSObject.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

unhide:

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

- (void)unhide:(id)sender
Parameters
sender

The object that sent the command.

Discussion

Invokes unhideWithoutActivation.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

unhideAllApplications:

Unhides all applications, including the receiver.

- (void)unhideAllApplications:(id)sender
Parameters
sender

The object that sent this message.

Discussion

This action causes each application to order its windows to the front, which could obscure the currently active window in the active application.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

unhideWithoutActivation

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

- (void)unhideWithoutActivation
Discussion

When this method begins, it posts an NSApplicationWillUnhideNotification to the default notification center. If it completes successfully, it posts an NSApplicationDidUnhideNotification.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

unregisterForRemoteNotifications

Unregister for notifications received from Apple Push Notification service.

- (void)unregisterForRemoteNotifications
Discussion

You should only call this method in rare circumstances, such as when a new version of the application drops support for remote notifications. Applications unregistered through this method can always re-register.

Availability
  • Available in OS X v10.7 and later.
Declared In
NSApplication.h

unregisterUserInterfaceItemSearchHandler:

Unregister an an object that provides help data to your application.

- (void)unregisterUserInterfaceItemSearchHandler:(id<NSUserInterfaceItemSearching>)handler
Parameters
handler

The class instance that conforms to NSUserInterfaceItemSearching and provides help content.

Discussion

If you unregister the same instance more than once the subsequent invocations are ignored. Unregistering an instance that was never registered is ignored.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSUserInterfaceItemSearching.h

updateWindows

Sends an update message to each onscreen window.

- (void)updateWindows
Discussion

This method is invoked automatically in the main event loop after each event when running in NSDefaultRunLoopMode or NSModalRunLoopMode. This method is not invoked automatically when running in NSEventTrackingRunLoopMode.

When this method begins, it posts an NSApplicationWillUpdateNotification to the default notification center. When it successfully completes, it posts an NSApplicationDidUpdateNotification.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplication.h

updateWindowsItem:

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

- (void)updateWindowsItem:(NSWindow *)aWindow
Parameters
aWindow

The window whose menu item is to be updated.

Discussion

You rarely need to invoke this method because it is invoked automatically when the edit status of an NSWindow object is set.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

userInterfaceLayoutDirection

Returns the layout direction of the user interface.

- (NSUserInterfaceLayoutDirection)userInterfaceLayoutDirection
Return Value

The direction of the user interface layout. See NSUserInterfaceLayoutDirection for possible values.

Discussion

This method specifies the general user interface layout flow directions.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

validRequestorForSendType:returnType:

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

- (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
Parameters
sendType

The pasteboard type the application needs to send.

returnType

The pasteboard type the application needs to receive.

Return Value

The object that can send and receive the specified types or nil if the receiver knows of no object that can send and receive data of that type.

Discussion

This message is sent to all responders in a responder chain. NSApp is typically the last item in the responder chain, so it usually receives this message only if none of the current responders can send sendType data and accept back returnType data.

The receiver passes this message on to its delegate if the delegate can respond (and isn’t an NSResponder object with its own next responder). If the delegate cannot respond or returns nil, this method returns nil. If the delegate can find an object that can send sendType data and accept back returnType data, it returns that object.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

windows

Returns an array containing the receiver’s window objects.

- (NSArray *)windows
Return Value

An array of NSWindow objects. This array includes both onscreen and offscreen windows.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

windowsMenu

Returns the Window menu of the application.

- (NSMenu *)windowsMenu
Return Value

The window menu or nil if such a menu does not exist or has not yet been created.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

windowWithWindowNumber:

Returns the window corresponding to the specified window number.

- (NSWindow *)windowWithWindowNumber:(NSInteger)windowNum
Parameters
windowNum

The unique window number associated with the desired NSWindow object.

Return Value

The desired window object or nil if the window could not be found.

Discussion

windowWithWindowNumber: may return nil for window numbers found using windowNumbersWithOptions: if there is no corresponding window object owned by your app—for example, the menu bar.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

Delegate Methods

application:delegateHandlesKey:

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.

- (BOOL)application:(NSApplication *)sender delegateHandlesKey:(NSString *)key
Parameters
sender

The application object associated with the delegate.

key

The key to be handled.

Return Value

YES if your delegate handles the key or NO if it does not.

Discussion

The method should return YES if the delegate for the application sender handles the key specified by key, which means it can get or set the scriptable property or element that corresponds to that key. The application implements methods for each of the keys that it handles, where the method name matches the key.

For example, a scriptable application that doesn’t use Cocoa’s document-based application architecture can implement this method to supply its own document ordering. Such an application might want to do this because the standard application delegate expects to work with a document-based application. The TextEdit application (whose source is distributed with Mac OS X developer tools) provides the following implementation:

return [key isEqualToString:@"orderedDocuments"];

TextEdit then implements the orderedDocuments method in its controller class to return an ordered list of documents. An application with its own window ordering might add a test for the key orderedWindows so that its delegate can provide its own version of orderedWindows.

Availability
  • Available in OS X v10.0 and later.
See Also
Declared In
NSApplicationScripting.h

Constants

NSApp

A global constant for the shared application instance.

id NSApp
Constants
NSApp

Global constant for the shared application instance. This is the same as sending the NSApplication class the method sharedApplication message.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

Discussion

This variable designates the shared application object, created by the sharedApplication method.

NSUserInterfaceLayoutDirection

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

enum {
   NSUserInterfaceLayoutDirectionLeftToRight = 0,
   NSUserInterfaceLayoutDirectionRightToLeft = 1
};
typedef NSInteger NSUserInterfaceLayoutDirection;
Constants
NSUserInterfaceLayoutDirectionLeftToRight

Layout direction is left to right.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSUserInterfaceLayoutDirectionRightToLeft

Layout direction is right to left. This is appropriate when running with localizations such as Arabic or Hebrew that should have the user interface layout origin on the right edge of the coordinate system.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

NSModalResponse

Return values for -runModalForWindow: and runModalSession:.

enum {
   NSModalResponseStop                 = (-1000),s
   NSModalResponseAbort                = (-1001),
   NSModalResponseContinue             = (-1002),
};
typedef NSInteger NSModalResponse;
Constants
NSModalResponseStop

Modal session was broken with stopModal.

This constant is also used as the default response for sheet.

Available in OS X v10.9 and later.

Declared in NSApplication.h.

NSModalResponseAbort

Modal session was broken with abortModal.

Available in OS X v10.9 and later.

Declared in NSApplication.h.

NSModalResponseContinue

Modal session is continuing (returned by runModalSession: only).

Available in OS X v10.9 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.9 and later.
Declared In
NSApplication.h

Return values for modal operations

Historical return values for runModalForWindow: and runModalSession:.

enum {
   NSRunStoppedResponse    = (-1000),
   NSRunAbortedResponse    = (-1001),
   NSRunContinuesResponse  = (-1002)
};
Constants
NSRunStoppedResponse

Modal session was broken with stopModal. (Deprecated. Use NSModalResponseStop instead.)

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSRunAbortedResponse

Modal session was broken with abortModal. (Deprecated. Use NSModalResponseAbort instead.)

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSRunContinuesResponse

Modal session is continuing (returned by runModalSession: only). (Deprecated. Use NSModalResponseContinue instead.)

Available in OS X v10.0 and later.

Declared in NSApplication.h.

Discussion

The system also reserves all values below these.

NSUpdateWindowsRunLoopOrdering

This constant is used by the NSRunLoop method performSelector:target:argument:order:modes:.

enum {
   NSUpdateWindowsRunLoopOrdering = 500000
};
Constants
NSUpdateWindowsRunLoopOrdering

Run-loop message priority for handling window updates.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSRequestUserAttentionType

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

enum {
   NSCriticalRequest = 0,
   NSInformationalRequest = 10
}
typedef NSUInteger NSRequestUserAttentionType;
Constants
NSCriticalRequest

The user attention request is a critical request.

The dock icon will bounce until either the application becomes active or the request is canceled.

Available in OS X v10.1 and later.

Declared in NSApplication.h.

NSInformationalRequest

The user attention request is an informational request.

The dock icon will bounce for one second. The request, though, remains active until either the application becomes active or the request is canceled.

Available in OS X v10.1 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.1 and later.
Declared In
NSApplication.h

NSApplicationDelegateReply

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

enum NSApplicationDelegateReply {
   NSApplicationDelegateReplySuccess = 0,
   NSApplicationDelegateReplyCancel = 1,
   NSApplicationDelegateReplyFailure = 2
}
typedef NSUInteger NSApplicationDelegateReply;
Constants
NSApplicationDelegateReplySuccess

Indicates the operation succeeded.

Available in OS X v10.3 and later.

Declared in NSApplication.h.

NSApplicationDelegateReplyCancel

Indicates the user cancelled the operation.

Available in OS X v10.3 and later.

Declared in NSApplication.h.

NSApplicationDelegateReplyFailure

Indicates an error occurred processing the operation.

Available in OS X v10.3 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.3 and later.
Declared In
NSApplication.h

NSApplicationPresentationOptions

The constants control the presentation of the application. Typically, in fullscreen applications such as games or kiosks. They are used by the methods presentationOptions, currentSystemPresentationOptions, and setPresentationOptions:.

enum {
   NSApplicationPresentationDefault                    = 0,
   NSApplicationPresentationAutoHideDock               = (1 <<  0),
   NSApplicationPresentationHideDock                   = (1 <<  1),
   NSApplicationPresentationAutoHideMenuBar            = (1 <<  2),
   NSApplicationPresentationHideMenuBar                = (1 <<  3),
   NSApplicationPresentationDisableAppleMenu           = (1 <<  4),
   NSApplicationPresentationDisableProcessSwitching    = (1 <<  5),
   NSApplicationPresentationDisableForceQuit           = (1 <<  6),
   NSApplicationPresentationDisableSessionTermination  = (1 <<  7),
   NSApplicationPresentationDisableHideApplication     = (1 <<  8),
   NSApplicationPresentationDisableMenuBarTransparency = (1 <<  9)
   NSApplicationPresentationFullScreen                 = (1 << 10),
   NSApplicationPresentationAutoHideToolbar            = (1 << 11)
};
typedef NSUInteger NSApplicationPresentationOptions;
Constants
NSApplicationPresentationDefault

This is the default presentation mode. The application is displayed as normal, including dock, menu bar, process switching is enabled, force quit is enabled, session termination is enabled, the hide menu is enabled, and the menu bar transparency is normal.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationAutoHideDock

The dock is normally hidden, but automatically appears when moused near.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationHideDock

The dock is entirely hidden and disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationAutoHideMenuBar

The menu bar is normally hidden, but automatically appears when moused near.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationHideMenuBar

The menu bar is entirely hidden and disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationDisableAppleMenu

All Apple Menu items are disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationDisableProcessSwitching

The process switching user interface (Command + Tab to cycle through applications) is disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationDisableForceQuit

The force quit panel (displayed by pressing Command + Option + Esc) is disabled

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationDisableSessionTermination

The panel that shows the Restart, Shut Down, and Log Out options that are displayed as a result of pushing the power key is disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationDisableHideApplication

The application’s “Hide” menu item is disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationDisableMenuBarTransparency

The menu bar transparency appearance is disabled.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSApplicationPresentationFullScreen

The application is in fullscreen mode.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSApplicationPresentationAutoHideToolbar

When in fullscreen mode the window toolbar is detached from window and hides and shows with autoHidden menuBar.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

Discussion

There are restrictions on the combination of presentation options that can be set simultaneously:

When setPresentationOptions: receives a parameter value that does not conform to these requirements, it raises an NSInvalidArgumentException.

Availability
  • Available in OS X v10.6 and later.
Declared In
NSApplication.h

NSApplicationTerminateReply

These constants define whether an application should terminate and are used by the delegate method applicationShouldTerminate:.

enum {
   NSTerminateCancel = 0,
   NSTerminateNow    = 1,
   NSTerminateLater  = 2
}
typedef NSUInteger NSApplicationTerminateReply;
Constants
NSTerminateNow

It is OK to proceed with termination.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSTerminateCancel

The application should not be terminated.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSTerminateLater

It may be OK to proceed with termination later. Returning this value causes Cocoa to run the run loop in the NSModalPanelRunLoopMode until your application subsequently calls replyToApplicationShouldTerminate: with the value YES or NO. This return value is for delegates that need to provide document modal alerts (sheets) in order to decide whether to quit.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSApplication.h

NSApplicationPrintReply

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

enum {
   NSPrintingCancelled  = 0,
   NSPrintingSuccess    = 1,
   NSPrintingFailure    = 3,
   NSPrintingReplyLater = 2
}
typedef NSUInteger NSApplicationPrintReply;
Constants
NSPrintingCancelled

Printing was cancelled.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSPrintingSuccess

Printing was successful.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSPrintingFailure

Printing failed.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSPrintingReplyLater

The result of printing cannot be returned immediately, for example, if printing will cause the presentation of a sheet. If your method returns NSPrintingReplyLater it must always invoke replyToOpenOrPrint: when the entire print operation has been completed, successfully or not.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.4 and later.
Declared In
NSApplication.h

Run loop modes

These loop mode constants are defined by NSApplication.

NSString *NSModalPanelRunLoopMode;
NSString *NSEventTrackingRunLoopMode;
Constants
NSEventTrackingRunLoopMode

A run loop should be set to this mode when tracking events modally, such as a mouse-dragging loop.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSModalPanelRunLoopMode

A run loop should be set to this mode when waiting for input from a modal panel, such as NSSavePanel or NSOpenPanel.

Available in OS X v10.0 and later.

Declared in NSApplication.h.

NSApplicationDidFinishLaunching User Info Keys

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

NSString * const NSApplicationLaunchRemoteNotificationKey;
NSString * const NSApplicationLaunchIsDefaultLaunchKey;
NSString * const NSApplicationLaunchUserNotificationKey;
Constants
NSApplicationLaunchRemoteNotificationKey

Use this key to access the JSON push-notification payload from the userInfo dictionary of the NSApplicationDidFinishLaunchingNotification notification. This notification is passed into the delegate method application:didFinishLaunching: declared by the NSApplicationDelegate Protocol protocol to handle this notification. For information about the payload dictionary, see Local and Push Notification Programming Guide.

Available in OS X v10.7 and later.

Deprecated in OS X v10.8.

Declared in NSApplication.h.

NSApplicationLaunchIsDefaultLaunchKey

The value for this key is an NSNumber containing a Boolean value. The value is NO if the application was launched to open or print a file, to perform a Service action, if the application had saved state that will be restored, or if the application launch was in some other sense not a default launch. Otherwise its value will be YES.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSApplicationLaunchUserNotificationKey

The following key is an NSUserNotification object that will be present in the notification userInfo dictionary of the NSApplicationDidFinishLaunchingNotification notification if your application was launched because a user activated a notification in the Notification Center.

Available in OS X v10.8 and later.

Declared in NSApplication.h.

NSRemoteNotificationType

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

enum {
   NSRemoteNotificationTypeNone    = 0,
   NSRemoteNotificationTypeBadge   = 1 << 0
   NSRemoteNotificationTypeSound   = 1 << 1,
   NSRemoteNotificationTypeAlert   = 1 << 2,
};
typedef NSUInteger NSRemoteNotificationType;
Constants
NSRemoteNotificationTypeNone

The application should not display a badge.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSRemoteNotificationTypeBadge

The application should display a badge.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSRemoteNotificationTypeSound

The application should play a sound.

Available in OS X v10.8 and later.

Declared in NSApplication.h.

NSRemoteNotificationTypeAlert

The application should display an alert.

Available in OS X v10.8 and later.

Declared in NSApplication.h.

NSApplicationOcclusionState

This constants indicates whether at least part of any window owned by this application is visible.

typedef NS_OPTIONS(NSUInteger, NSApplicationOcclusionState) {
   NSApplicationOcclusionStateVisible = 1UL << 1, }
Constants
NSApplicationOcclusionStateVisible

If set, at least part of any window owned by this application is visible.

If not set, all parts of all windows owned by this application are completely occluded. The menu bar does not count as a window owned by this application, so if only the menu bar is showing then the application is considered not visible. Status items, however, have windows owned by your application. If the status item is present in the menu bar, your application will be considered visible as long as the menu bar is visible.

Available in OS X v10.9 and later.

Declared in NSApplication.h.

Availability
  • Available in OS X v10.9 and later.
Declared In
NSApplication.h

NSAppKitVersionNumber

This constant identifies the installed version of the Application Kit framework.

const double NSAppKitVersionNumber;
Constants
NSAppKitVersionNumber

This value corresponds to one of the constants defined in “Application Kit framework version numbers.”

Available in OS X v10.1 and later.

Declared in NSApplication.h.

Application Kit framework version numbers

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

#define NSAppKitVersionNumber10_0   577
#define NSAppKitVersionNumber10_1   620
#define NSAppKitVersionNumber10_2   663
#define NSAppKitVersionNumber10_2_3 663.6
#define NSAppKitVersionNumber10_3   743
#define NSAppKitVersionNumber10_3_2 743.14
#define NSAppKitVersionNumber10_3_3 743.2
#define NSAppKitVersionNumber10_3_5 743.24
#define NSAppKitVersionNumber10_3_7 743.33
#define NSAppKitVersionNumber10_3_9 743.36
#define NSAppKitVersionNumber10_4   824
#define NSAppKitVersionNumber10_4_1 824.1
#define NSAppKitVersionNumber10_4_3 824.23
#define NSAppKitVersionNumber10_4_4 824.33
#define NSAppKitVersionNumber10_4_7 824.41
#define NSAppKitVersionNumber10_5   949
#define NSAppKitVersionNumber10_5_2 949.27
#define NSAppKitVersionNumber10_5_3 949.33
#define NSAppKitVersionNumber10_6 1038
#define NSAppKitVersionNumber10_7 1138
#define NSAppKitVersionNumber10_7_2 1138.23
Constants
NSAppKitVersionNumber10_0

The Application Kit framework included in OS X v10.0.

Available in OS X v10.1 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_1

The Application Kit framework included in OS X v10.1.

Available in OS X v10.2 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_2

The Application Kit framework included in OS X v10.2.

Available in OS X v10.3 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_2_3

The Application Kit framework included in OS X v10.2.3.

Available in OS X v10.3 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_3

The Application Kit framework included in OS X v10.3.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_3_2

The Application Kit framework included in OS X v10.3.2.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_3_3

The Application Kit framework included in OS X v10.3.3.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_3_5

The Application Kit framework included in OS X v10.3.5.

Available in OS X v10.4 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_3_7

The Application Kit framework included in OS X v10.3.7.

Available in OS X v10.5 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_3_9

The Application Kit framework included in OS X v10.3.9.

Available in OS X v10.5 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_4

The Application Kit framework included in OS X v10.4.

Available in OS X v10.5 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_4_1

The Application Kit framework included in OS X v10.4.1.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_4_3

The Application Kit framework included in OS X v10.4.3.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_4_4

The Application Kit framework included in OS X v10.4.4.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_4_7

The Application Kit framework included in OS X v10.4.7.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_5

The Application Kit framework included in OS X v10.5.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_5_2

The Application Kit framework included in OS X v10.5.2.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_5_3

The Application Kit framework included in OS X v10.5.3.

Available in OS X v10.6 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_6

The Application Kit framework included in OS X v10.6.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_7

The Application Kit framework included in OS X v10.7.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_7_2

The Application Kit framework included in OS X v10.7.2.

Available in OS X v10.7 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_7_3

The Application Kit framework included in OS X v10.7.3.

Available in OS X v10.9 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_7_4

The Application Kit framework included in OS X v10.7.4.

Available in OS X v10.9 and later.

Declared in NSApplication.h.

NSAppKitVersionNumber10_8

The Application Kit framework included in OS X v10.8.

Available in OS X v10.9 and later.

Declared in NSApplication.h.

Notifications

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

NSApplicationDidBecomeActiveNotification

Posted immediately after the application becomes active.

The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationDidChangeScreenParametersNotification

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

The configuration change can be made either programmatically or when the user changes settings in the Displays control panel. The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationDidFinishLaunchingNotification

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

The notification object is sharedApplication. See “NSApplicationDidFinishLaunching User Info Keys” for the possible userInfo keys and values.

Availability
Declared In
NSApplication.h

NSApplicationDidHideNotification

Posted at the end of the hide: method to indicate that the application is now hidden.

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationDidResignActiveNotification

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

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationDidUnhideNotification

Posted at the end of the unhideWithoutActivation method to indicate that the application is now visible.

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationDidUpdateNotification

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

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillBecomeActiveNotification

Posted immediately before the application becomes active.

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillFinishLaunchingNotification

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

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillHideNotification

Posted at the start of the hide: method to indicate that the application is about to be hidden.

The notification object is NSApp. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillResignActiveNotification

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

The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillTerminateNotification

Posted by the terminate: method to indicate that the application will terminate.

Posted only if the delegate method applicationShouldTerminate: returns YES. The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillUnhideNotification

Posted at the start of the unhideWithoutActivation method to indicate that the application is about to become visible.

The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationWillUpdateNotification

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

The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSApplication.h

NSApplicationDidFinishRestoringWindowsNotification

Posted when the application is finished restoring windows.

The notification is posted when the application is finished restoring windows, that is, when all the completion handlers from restoreWindowWithIdentifier:state:completionHandler: have been called. This is always posted after NSApplicationWillFinishLaunchingNotification, but may be posted before or after NSApplicationDidFinishLaunchingNotification, depending on whether clients copy the completion handlers and invoke them later. If there were no windows to restore, then this notification is still posted at the corresponding point in app launch (between NSApplicationWillFinishLaunchingNotification and NSApplicationDidFinishLaunchingNotification).

The notification object is sharedApplication. This notification does not contain a userInfo dictionary.

Availability
Declared In
NSWindowRestoration.h

NSApplicationDidChangeOcclusionStateNotification

Posted when the application’s occlusion state changes.

Upon receiving this notification, you can query the application for its occlusion state. Note that this only notifies about changes in the state of the occlusion, not when the occlusion region changes. You can use this notification to increase responsiveness and save power by halting any expensive calculations that the user can not see.

Availability
Declared In
NSApplication.h