| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/AppKit.framework |
| Availability | Available in Mac OS X v10.0 and later.
|
| Declared in | NSApplication.h NSApplicationScripting.h NSColorPanel.h NSHelpManager.h NSPageLayout.h |
| Companion guides |
An NSApplication object manages an application’s main event loop in addition to resources used by all of that application’s objects.
Delegate
Key window
Display context
List of windows
Main window
keyWindowReturns an NSWindow object representing the key window.
mainWindowReturns 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.
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, Mac 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 pools (instances of the NSAutoreleasePool class) 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 pools during the loading of nib files. These autorelease pools 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 pool before using the classes and then release the pool when you’re done. For more information, see NSAutoreleasePool in the Foundation Framework Reference.
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:.
NSApplication interacts with the system services architecture to provide services to your application through the Services menu.
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.
Important: Many Application Kit classes rely on the NSApplication class and may not work properly until this class is fully initialized. As a result, you should not, for example, attempt to invoke methods of other Application Kit classes from an initialization method of an NSApplication subclass.
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:
Override run if you want the application to manage the main event loop differently than it does by default. (This a critical and complex task, however, that you should only attempt with good reason.)
Override sendEvent: if you want to change how events are dispatched or perform some special event processing.
Override requestUserAttention: if you want to modify how your application attracts the attention of the user (for example, offering an alternative to the bouncing application icon in the Dock).
Override targetForAction: to substitute another object for the target of an action message.
The global application object uses autorelease pools in its run method; if you override this method, you’ll need to create your own autorelease pools.
Do not override sharedApplication. The default implementation, which is essential to application behavior, is too complex to duplicate on your own.
NSApplication defines over twenty 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. For more about application architectures, see Cocoa Design Patterns and The Core Application Architecture.
– finishLaunching
– applicationWillFinishLaunching: delegate method
– applicationDidFinishLaunching: delegate method
– terminate:
– applicationShouldTerminate: delegate method
– applicationShouldTerminateAfterLastWindowClosed: delegate method
– replyToApplicationShouldTerminate:
– applicationWillTerminate: delegate method
– isActive
– activateIgnoringOtherApps:
– applicationWillBecomeActive: delegate method
– applicationDidBecomeActive: delegate method
– deactivate
– applicationWillResignActive: delegate method
– applicationDidResignActive: delegate method
– hideOtherApplications:
– unhideAllApplications:
– applicationWillHide: delegate method
– applicationDidHide: delegate method
– applicationWillUnhide: delegate method
– applicationDidUnhide: delegate method
– isRunning
– run
– stop:
– runModalForWindow:
– stopModal
– stopModalWithCode:
– abortModal
– beginModalSessionForWindow:
– runModalSession:
– modalWindow
– endModalSession:
– sendEvent:
– currentEvent
– nextEventMatchingMask:untilDate:inMode:dequeue:
– discardEventsMatchingMask:beforeEvent:
– beginSheet:modalForWindow:modalDelegate:didEndSelector:contextInfo:
– endSheet:
– endSheet:returnCode:
– keyWindow
– mainWindow
– windowWithWindowNumber:
– windows
– makeWindowsPerform:inOrder:
– applicationWillUpdate: delegate method
– applicationDidUpdate: delegate method
– applicationShouldHandleReopen:hasVisibleWindows: delegate method
– windowsMenu
– setWindowsMenu:
– addWindowsItem:title:filename:
– changeWindowsItem:title:filename:
– removeWindowsItem:
– updateWindowsItem:
– applicationDockMenu: delegate method
– orderFrontColorPanel:
– orderFrontStandardAboutPanel:
– orderFrontStandardAboutPanelWithOptions:
– orderFrontCharacterPalette:
– runPageLayout:
– application:willPresentError: delegate method
– orderedDocuments
– orderedWindows
– application:delegateHandlesKey: delegate method
– applicationDidChangeScreenParameters: delegate method
– application:openFile: delegate method
– application:openFileWithoutUI: delegate method
– application:openTempFile: delegate method
– application:openFiles: delegate method
– applicationOpenUntitledFile: delegate method
– applicationShouldOpenUntitledFile: delegate method
– application:printFile: delegate method
– application:printFiles:withSettings:showPrintPanels: delegate method
– runModalForWindow:relativeToWindow:
– beginModalSessionForWindow:relativeToWindow:
– application:printFiles: delegate method Deprecated in Mac OS X v10.4
Creates and executes a new thread, automatically creating an NSAutoreleasePool object for the thread. This method is a convenience wrapper for the NSThread method detachNewThreadSelector:toTarget:withObject:.
+ (void)detachDrawingThread:(SEL)selector toTarget:(id)target withObject:(id)argument
NSApplication.h
Returns the NSApplication instance (the global variable NSApp), creating it if it doesn’t exist yet.
+ (NSApplication *)sharedApplication
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.
NSApplication.hAborts the event loop started by runModalForWindow: or runModalSession:.
- (void)abortModal
When stopped with this method, runModalForWindow: and runModalSession: return NSRunAbortedResponse.
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.
NSApplication.hPlaces the receiver in context-sensitive help mode.
- (void)activateContextHelpMode:(id)sender
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.
NSHelpManager.hMakes the receiver the active application.
- (void)activateIgnoringOtherApps:(BOOL)flag
If flag is NO, the application is activated only if no other application is currently active. If flag is YES, the application activates regardless.
The flag 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 interapplication 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.
NSApplication.hAdds an item to the Window menu for a given window.
- (void)addWindowsItem:(NSWindow *)aWindow title:(NSString *)aString filename:(BOOL)isFilename
If isFilename is NO, aString appears literally in the menu. If isFilename is YES, 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). If an item for aWindow already exists in the Window menu, this method has no effect. You rarely invoke this method because an item is placed in the Window menu for you whenever an NSWindow object’s title is set.
– changeWindowsItem:title:filename:– setTitle: (NSWindow)NSApplication.hReturns the NSImage object used for the receiver’s icon.
- (NSImage *)applicationIconImage
NSApplication.h
Arranges windows listed in the Window menu in front of all other windows.
- (void)arrangeInFront:(id)sender
Windows associated with the application but not listed in the Window menu are not ordered to the front.
NSApplication.hSets up a modal session with the given window and returns an NSModalSession structure representing the session.
- (NSModalSession)beginModalSessionForWindow:(NSWindow *)aWindow
The window for the session.
The NSModalSession structure that represents the session.
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.
NSApplication.h (Deprecated. Use beginSheet:modalForWindow:modalDelegate:didEndSelector:contextInfo: instead.)
- (NSModalSession)beginModalSessionForWindow:(NSWindow *)theWindow relativeToWindow:(NSWindow *)docWindow
NSApplication.hStarts a document modal session.
- (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo
The didEndSelector method is optional. If implemented by the modalDelegate, this method is invoked after the modal session has ended and is passed a return code and caller specified in contextInfo. didEndSelector should have the following signature:
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo; |
Use this method in cases where you do not need to do any additional background processing while your sheet runs. This method consumes only enough CPU time to process events and dispatch them to the action methods associated with the sheet. If you want to perform additional background processing, use runModalSession: together with an NSModalSession object instead.
NSApplication.hCancels a previous user attention request.
- (void)cancelUserAttentionRequest:(NSInteger)request
request is the return value from a previous call to requestUserAttention:. A request is also canceled automatically by user activation of the application.
NSApplication.hChanges the item for a given window in the Window menu to a given string.
- (void)changeWindowsItem:(NSWindow *)aWindow title:(NSString *)aString filename:(BOOL)isFilename
If aWindow doesn’t have an item in the Window menu, this method adds the item. If isFilename is NO, aString appears literally in the menu. If isFilename is YES, aString is assumed to be a converted pathname with the file’s name preceding the path (the way the NSWindow method setTitleWithRepresentedFilename: places a title).
NSApplication.hReturns the receiver’s display context.
- (NSGraphicsContext *)context
NSApplication.hReturns the current event, the last event the receiver retrieved from the event queue.
- (NSEvent *)currentEvent
NSApp receives events and forwards the current event to the affected NSWindow object, which then distributes it to the objects in its view hierarchy.
NSApplication.hDeactivates the receiver.
- (void)deactivate
Normally, you shouldn’t invoke this method—the Application Kit is responsible for proper deactivation.
NSApplication.hReturns the receiver’s delegate.
- (id)delegate
NSApplication.hRemoves all events matching the given mask and generated before a given event from the event queue.
- (void)discardEventsMatchingMask:(NSUInteger)mask beforeEvent:(NSEvent *)lastEvent
Typically, you send this message to an NSWindow object, rather than to NSApp.
mask can contain these constants: