NSAlert Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AppKit.framework
Availability
Available in OS X v10.3 and later.
Declared in
NSAlert.h
Companion guides
Related sample code

Overview

An NSAlert object displays an alert, either as an application-modal dialog or as a sheet attached to a document window. The methods of the NSAlert class allow you to specify alert level, icon, button titles, and alert text. The class also lets your alerts display help buttons and provides ways for applications to offer help specific to an alert. To display an alert as a sheet, call the beginSheetModalForWindow:completionHandler: method; to display one as an application-modal dialog, use the runModal method.

By design, an NSAlert object is intended for a single alert—that is, an alert with a unique combination of title, buttons, and so on—that is displayed upon a particular condition. You should create an NSAlert object for each alert dialog. Normally you should create an NSAlert object when you need to display an alert, and release it when you are done. If you have a particular alert dialog that you need to show repeatedly, you can retain and reuse an instance of NSAlert for this dialog.

After creating an alert using one of the alert creation methods, you can customize it further prior to displaying it by customizing its attributes. See “Instance Attributes”

Instance Attributes

NSAlert objects have the following attributes:

  • Type. An alert’s type helps convey the importance or gravity of its message to the user. Specified with setAlertStyle:.

  • Message text. The main message of the alert. Specified with setMessageText:.

  • Informative text. Additional information about the alert. Specified with informativeText.

  • Icon. The icon displayed in the alert. Specified with : setIcon:.

  • Help. Alerts can let the user get help about them. Use setHelpAnchor: and setShowsHelp:.

  • Response buttons. By default an alert has one response button: the OK button. You can add more response buttons using: addButtonWithTitle:.

  • Suppression checkbox. A suppression checkbox allows the user to suppress the display of a particular alert in subsequent occurrences of the event that triggers it. Use setShowsSuppressionButton:, suppressionButton.

  • Accessory view. An accessory view lets you add additional information to an alert; for example, a text field with contact information. Use setAccessoryView:, layout.

Subclassing Notes

The NSAlert class is not designed for subclassing.

Tasks

Creating Alerts

Configuring Alerts

Displaying Alerts

Accessing Alert Text

Accessing Alert Icons

Accessing Alert Buttons

Getting Alert Panels

Class Methods

alertWithError:

Returns an alert initialized from information in an error object.

+ (NSAlert *)alertWithError:(NSError *)error
Parameters
error

Error information to display.

Return Value

Initialized alert.

Discussion

The NSAlert class extracts the localized error description, recovery suggestion, and recovery options from error and uses them as the alert’s message text, informative text, and button titles, respectively.

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

alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:

Creates an alert compatible with alerts created using the NSRunAlertPanel function for display as a warning-style alert. (Deprecated. Instead, alloc and init an NSAlert object and set its attributes as appropriate.)

+ (NSAlert *)alertWithMessageText:(NSString *)messageTitle defaultButton:(NSString *)defaultButtonTitle alternateButton:(NSString *)alternateButtonTitle otherButton:(NSString *)otherButtonTitle informativeTextWithFormat:(NSString *)informativeText, ...
Parameters
messageTitle

Title of the alert. When nil or an empty string, a default localized title is used (“Alert” in English).

defaultButtonTitle

Title for the default button. When nil or an empty string, a default localized button title (“OK” in English) is used.

alternateButtonTitle

Title for the alternate button. When nil, the alternate button is not created.

otherButtonTitle

Title for the other button. When nil, the other button is not created.

informativeText

Informative text. This is optional but must be an empty string (@"") not nil. Can embed variable values using a format string; list any necessary arguments for this formatted string at the end of the method’s argument list. For more information on format strings, see “Formatting String Objects”.

Return Value

Initialized alert.

Discussion

For languages that read left to right, the buttons are laid out on the bottom-right corner of the alert sheet or window, with defaultButtonTitle on the right, alternateButtonTitle on the left, and otherButtonTitle in the middle. The return values identifying these buttons are constants— NSAlertDefaultReturn, NSAlertAlternateReturn, and NSAlertOtherReturn—that correspond to the keywords.

By default, the first button has a key equivalent of Return, any button with a title of “Cancel” has a key equivalent of Escape, and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it is not the first button). You can also assign different key equivalents for the buttons using the setKeyEquivalent: method of the NSButton class. To access the alert’s buttons, use the buttons method.

Special Considerations

This is a compatibility method. It is designed for easy adoption by applications migrating from the corresponding function-based API. This method uses earlier return values—NSAlertDefaultReturn, NSAlertAlternateReturn, and NSAlertOtherReturn—compatible with the earlier API, rather than the return values defined by the NSAlert class, described in “Button Return Values.”

Unless you must maintain compatibility with existing alert-processing code that uses the function-based API, you should allocate (alloc) and initialize (init) the object, and then set its attributes using the appropriate methods of the NSAlert class.

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

Instance Methods

accessoryView

Returns the receiver’s accessory view.

- (NSView *)accessoryView
Return Value

The alert’s accessory view.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSAlert.h

addButtonWithTitle:

Adds a button with a given title to the receiver.

- (NSButton *)addButtonWithTitle:(NSString *)buttonTitle
Parameters
buttonTitle

Title of the button to add to the alert. Must not be nil.

Return Value

Button added to the alert.

Discussion

Buttons are placed starting near the right side of the alert and going toward the left side (for languages that read left to right). The first three buttons are identified positionally as NSAlertFirstButtonReturn, NSAlertSecondButtonReturn, NSAlertThirdButtonReturn in the return-code parameter evaluated by the modal delegate. Subsequent buttons are identified as NSAlertThirdButtonReturn +n, where n is an integer

By default, the first button has a key equivalent of Return, any button with a title of “Cancel” has a key equivalent of Escape, and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it’s not the first button). You can also assign different key equivalents for the buttons using the setKeyEquivalent: method of the NSButton class. In addition, you can use the setTag: method of the NSButton class to set the return value.

Availability
  • Available in OS X v10.3 and later.
See Also
Declared In
NSAlert.h

alertStyle

Returns the NSAlertStyle constant identifying the receiver’s alert style.

- (NSAlertStyle)alertStyle
Return Value

Alert style for the alert. See NSAlertStyle for the list of alert style constants.

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

beginSheetModalForWindow:completionHandler:

Runs the alert modally as a sheet attached to the specified window.

- (void)beginSheetModalForWindow:(NSWindow *)sheetWindow completionHandler:(void (^)(NSModalResponse returnCode))handler
Parameters
sheetWindow

The window on which to display the sheet.

handler

The completion handler that gets called when the sheet’s modal session ends.

Discussion

This method uses the NSWindow sheet methods to display the alert (for more information, see “Managing Sheets” in NSWindow Class Reference). If the alert has an alert style of NSCriticalAlertStyle, it will be presented as a critical sheet, which means that it can display on top of other sheets that might already be attached to the window. Otherwise, it will be presented—or queued for presentation—as a standard sheet.

Note that orderOut: no longer needs to be called in the completion handler. If you don’t dismiss the alert, it will be done for you after the completion handler finishes.

Availability
  • Available in OS X v10.9 and later.
See Also
Declared In
NSAlert.h

beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:

Runs the receiver modally as an alert sheet attached to a specified window. (Deprecated. Use beginSheetModalForWindow:completionHandler: instead.)

- (void)beginSheetModalForWindow:(NSWindow *)window modalDelegate:(id)modalDelegate didEndSelector:(SEL)alertDidEndSelector contextInfo:(void *)contextInfo
Parameters
window

The parent window for the sheet.

modalDelegate

The delegate for the modal-dialog session.

alertDidEndSelector

Message the alert sends to modalDelegate after the user responds but before the sheet is dismissed.

contextInfo

Contextual data passed to modalDelegate in didEndSelector message.

Discussion

You can create the required NSAlert object either through the standard allocate-initialize procedure or by using the compatibility method alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:.

The alertDidEndSelector argument must be a selector that takes three arguments, and the corresponding method should have a declaration modeled on the following example:

- (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;

where alert is the NSAlert object, returnCode specifies which button the user clicked, and contextInfo is the same contextInfo passed in the original message. The returnCode argument identifies which button was used to dismiss the alert (see this method’s “Special Considerations” section). The modal delegate determines which button was clicked (“OK”, “Cancel”, and so on) and proceeds accordingly.

If you want to dismiss the sheet from within the alertDidEndSelector method before the modal delegate carries out an action in response to the return value, send orderOut: (NSWindow) to the window object obtained by sending window to the alert argument. This allows you to chain sheets, for example, by dismissing one sheet before showing the next from within the alertDidEndSelector method. Note that you should be careful not to call orderOut: on the sheet from elsewhere in your program before the alertDidEndSelector method is invoked because the parent window can hang when another alert is requested. If you need to do this, use the NSApplication method endSheet:.

Special Considerations

If you use alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: to create an alert, the following constants are used to identify the button used to dismiss the alert: NSAlertDefaultReturn, NSAlertAlternateReturn, and NSAlertOtherReturn. Otherwise, the constants used are the ones described in “Button Return Values.”

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

buttons

Returns the receiver’s buttons.

- (NSArray *)buttons
Return Value

The alert’s buttons. The rightmost button is at index 0.

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

delegate

Returns the receiver’s delegate.

- (id < NSAlertDelegate >)delegate
Return Value

The alert’s delegate.

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

helpAnchor

Returns the receiver’s HTML help anchor.

- (NSString *)helpAnchor
Return Value

The alert’s help anchor or nil when the alert has no help anchor.

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

icon

Returns the icon displayed in the receiver.

- (NSImage *)icon
Return Value

The alert’s icon.

Discussion

The default image is the application icon (NSApplicationIcon application property).

Availability
  • Available in OS X v10.3 and later.
See Also
Declared In
NSAlert.h

informativeText

Returns the receiver’s informative text.

- (NSString *)informativeText
Return Value

The alert’s informative text.

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

init

Returns an initialized alert.

- init
Return Value

Initialized alert.

Discussion

Unless you must maintain compatibility with existing alert-processing code that uses the function-based API, you should allocate (alloc) and initialize (init) the object, and then set its attributes using the appropriate methods of the NSAlert class.

layout

Specifies that the receiver must do immediate layout instead of lazily just before display.

- (void)layout
Discussion

You need to call this method only when you need to customize the alert’s layout. Call this method after all the alert’s attributes have been customized, including the suppression checkbox and the accessory layout. After the method returns, you can make the necessary layout changes; for example, adjusting the frame of the accessory view.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSAlert.h

messageText

Returns the receiver’s message text (or title).

- (NSString *)messageText
Return Value

The alert’s message text.

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

runModal

Runs the receiver as an application-modal dialog and returns the constant positionally identifying the button clicked.

- (NSInteger)runModal
Return Value

Response to the alert. See this method’s “Special Considerations” section for details.

Discussion

You can create the alert either through the standard allocate–initialize procedure or by using the compatibility method alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:.

Special Considerations

If you use alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: to create an alert, the following constants are used to identify the button used to dismiss the alert: NSAlertDefaultReturn, NSAlertAlternateReturn, and NSAlertOtherReturn. Otherwise, the constants used are the ones described in “Button Return Values.”

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

setAccessoryView:

Sets the receiver’s accessory view.

- (void)setAccessoryView:(NSView *)accessoryView
Parameters
accessoryView

View that is to be the alert’s accessory view.

Discussion

The NSAlert class places the accessory view between the informative text or suppression checkbox (if present) and the response buttons. To change the location of the accessory view, you must first call the layout method.

Listing 1 shows an example of adding an accessory view to an alert. Figure 1 shows the alert generated.

Listing 1  Adding an accessory view to an alert

NSTextView *accessory = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,200,15)];
NSFont *font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
NSDictionary *textAttributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
[accessory insertText:[[NSAttributedString alloc] initWithString:@"Text in accessory view."
                                                      attributes:textAttributes]];
[accessory setEditable:NO];
[accessory setDrawsBackground:NO];
 
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Message text."];
[alert setInformativeText:@"Informative text."];
[alert setAccessoryView:accessory];
[alert runModal];
[alert release;
Figure 1  Alert dialog with an accessory view
Availability
  • Available in OS X v10.5 and later.
Related Sample Code
Declared In
NSAlert.h

setAlertStyle:

Sets the alert style of the receiver.

- (void)setAlertStyle:(NSAlertStyle)style
Parameters
style

Alert style for the alert. Indicates the severity level of the alert. See NSAlertStyle for the list of alert style constants.

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

setDelegate:

Sets the receiver’s delegate.

- (void)setDelegate:(id < NSAlertDelegate >)delegate
Parameters
delegate

The delegate for the alert or nil to remove the delegate.

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

setHelpAnchor:

Associates the receiver to a given anchor.

- (void)setHelpAnchor:(NSString *)anchor
Parameters
anchor

The help anchor to associate with the alert or nil to remove the associated help anchor.

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

setIcon:

Sets the icon to be displayed in the alert to a given icon.

- (void)setIcon:(NSImage *)icon
Parameters
icon

Icon for the alert. nil restores the application icon.

Discussion

By default, the image is the application icon, accessed through the application bundle’s NSApplicationIcon property.

Availability
  • Available in OS X v10.3 and later.
See Also
Declared In
NSAlert.h

setInformativeText:

Sets the receiver’s informative text to a given text.

- (void)setInformativeText:(NSString *)informativeText
Parameters
informativeText

Informative text for the alert. The value must not be nil.

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

setMessageText:

Sets the receiver’s message text, or title, to a given text.

- (void)setMessageText:(NSString *)messageText
Parameters
messageText

Message text for the alert.

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

setShowsHelp:

Specifies whether the receiver has a help button.

- (void)setShowsHelp:(BOOL)showsHelp
Parameters
showsHelp

YES for a help button, NO for no help button.

Discussion

When the help button is clicked, the alert delegate (delegate) is first sent a alertShowHelp: message. If there is no delegate, or the delegate does not implement alertShowHelp: or returns NO, then the openHelpAnchor:inBook: message is sent to the application’s help manager with a nil book and the anchor specified by setHelpAnchor:, if any. An exception is raised if the delegate returns NO and no help anchor is set.

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

setShowsSuppressionButton:

Specifies whether the receiver includes a suppression checkbox.

- (void)setShowsSuppressionButton:(BOOL)showButton
Parameters
showButton

When YES the alert includes the suppression checkbox.

Discussion

You can set the title of the checkbox with the following code:

[[alert suppressionButton] setTitle:title];

Listing 2 shows how to add a suppression checkbox to a modal alert. Figure 2 shows the corresponding dialog.

Listing 2  Creating an alert with a suppression checkbox

NSString *exampleAlertSuppress = @"ExampleAlertSuppress";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:exampleAlertSuppress]) {
    NSLog(@"ExampleAlert suppressed");
}
else {
 
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"Message text."];
    [alert setInformativeText:@"Informative text."];
    [alert setShowsSuppressionButton:YES];
    [alert runModal];
    if ([[alert suppressionButton] state] == NSOnState) {
        // Suppress this alert from now on.
        [defaults setBool:YES forKey:exampleAlertSuppress];
    }
    [alert release];
}
Figure 2  Alert dialog with a suppression checkbox
Availability
  • Available in OS X v10.5 and later.
Related Sample Code
Declared In
NSAlert.h

showsHelp

Indicates whether the receiver has a help button.

- (BOOL)showsHelp
Return Value

YES if the alert has a help button, NO otherwise.

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

showsSuppressionButton

Indicates whether the receiver shows a suppression button.

- (BOOL)showsSuppressionButton
Return Value

YES when the alert shows a suppression button, NO otherwise. The default is NO.

Availability
  • Available in OS X v10.5 and later.
Declared In
NSAlert.h

suppressionButton

Returns the receiver’s suppression checkbox.

- (NSButton *)suppressionButton
Return Value

The alert’s suppression button.

Discussion

Use this method to customize the alert’s suppression checkbox before the alert is displayed. For example, you can change the title of the checkbox or specify its initial state, which is unselected by default.

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

window

Returns the application-modal panel or document-modal sheet that corresponds to this alert.

- (id)window
Return Value

The receiver’s associated NSPanel object.

Discussion

This method is useful when you want to dismiss an alert created with beginSheetModalForWindow:completionHandler: within the completion handler block.

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

Constants

NSAlertStyle

The NSAlert class defines the alert styles used by setAlertStyle: and alertStyle.

enum {
   NSWarningAlertStyle = 0,
   NSInformationalAlertStyle = 1,
   NSCriticalAlertStyle = 2
};
typedef NSUInteger NSAlertStyle;
Constants
NSWarningAlertStyle

An alert used to warn the user about a current or impending event. The purpose is more than informational but not critical. This is the default alert style.

Available in OS X v10.3 and later.

Declared in NSAlert.h.

NSInformationalAlertStyle

An alert used to inform the user about a current or impending event.

Available in OS X v10.3 and later.

Declared in NSAlert.h.

NSCriticalAlertStyle

Reserved this style for critical alerts, such as when there might be severe consequences as a result of a certain user response (for example, a “clean install” will erase all data on a volume). This style causes the icon to be badged with a caution icon.

Available in OS X v10.3 and later.

Declared in NSAlert.h.

Discussion

Currently, there is no visual difference between informational and warning alerts. You should only use the critical (or “caution”) alert style if warranted, as specified in the “Alerts” chapter in OS X Human Interface Guidelines.

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

Button Return Values

An alert’s return values for buttons are position dependent. The following constants describe the return values for the first three buttons on an alert (assuming a language that reads left to right).

enum {
   NSAlertFirstButtonReturn  = 1000,
   NSAlertSecondButtonReturn  = 1001,
   NSAlertThirdButtonReturn  = 1002
};
Constants
NSAlertFirstButtonReturn

The user clicked the first (rightmost) button on the dialog or sheet.

Available in OS X v10.3 and later.

Declared in NSAlert.h.

NSAlertSecondButtonReturn

The user clicked the second button from the right edge of the dialog or sheet.

Available in OS X v10.3 and later.

Declared in NSAlert.h.

NSAlertThirdButtonReturn

The user clicked the third button from the right edge of the dialog or sheet.

Available in OS X v10.3 and later.

Declared in NSAlert.h.

Discussion

If you have more than three buttons on your alert, the button-position return value is NSAlertThirdButtonReturn + n, where n is an integer. For languages that read right to left, the first button’s position is closest to the left edge of the dialog or sheet.

Declared In
NSAlert.h