Mac Developer Library

Developer

AppKit Framework Reference NSAlert Class Reference

Options
Deployment Target:

On This Page
Language:

NSAlert

An alert appears onscreen either as an app-modal dialog or as a sheet attached to a document window. The methods of the NSAlert class allow you to specify alert level, alert text, button titles, and a custom icon should you require it. The class also lets your alerts display a help button and provides ways for apps to offer help specific to an alert.

To display an alert as a sheet, call the beginSheetModalForWindow:completionHandler: method; to display one as an app-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 the alertStyle property.

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

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

  • Icon An optional, custom icon to display in the alert, which is used instead of the default app icon. Specified with icon.

  • Help Alerts can let the user get help about them. Use helpAnchor and showsHelp.

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

  • 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 showsSuppressionButton.

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

Subclassing Notes

The NSAlert class is not designed for subclassing.

Inheritance


Conforms To


Import Statement


Swift

import AppKit

Objective-C

@import AppKit;

Availability


Available in OS X v10.3 and later.
  • Returns an initialized alert.

    Declaration

    Objective-C

    - init

    Return Value

    An 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 alert object, and then set its attributes using the appropriate methods of the NSAlert class.

  • Returns an alert initialized from information in an error object.

    Declaration

    Swift

    init(error error: NSError) -> NSAlert

    Objective-C

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

    Parameters

    error

    Error information to display.

    Return Value

    An initialized alert.

    Discussion

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.4 and later.

  • Creates an alert compatible with alerts created using the NSRunAlertPanel function for display as a warning-style alert.

    Deprecation Statement

    Instead, alloc and init an NSAlert object and set its attributes as appropriate.

    Declaration

    Objective-C

    + (NSAlert *)alertWithMessageText:(NSString *)message defaultButton:(NSString *)defaultButton alternateButton:(NSString *)alternateButton otherButton:(NSString *)otherButton informativeTextWithFormat:(NSString *)format, ...

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

    Special Considerations

    This is a compatibility method. It is designed for easy adoption by apps 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.

    Import Statement

    Objective-C

    @import AppKit;

    Availability

    Available in OS X v10.3 and later.

    Deprecated in OS X v10.10.

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

    Declaration

    Swift

    func layout()

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.5 and later.

    See Also

    accessoryView

  • Indicates the alert’s severity level.

    Declaration

    Swift

    var alertStyle: NSAlertStyle

    Objective-C

    @property NSAlertStyle alertStyle

    Discussion

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • The alert’s accessory view.

    Declaration

    Swift

    var accessoryView: NSView?

    Objective-C

    @property(strong) NSView *accessoryView

    Discussion

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

    Adding an accessory view to an alert shows an example of adding an accessory view to an alert. Alert dialog with an accessory view shows the alert generated.

    Listing 1Adding 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.messageText = @"Message text.";
    • [alert setInformativeText:@"Informative text."];
    • alert.accessoryView = accessory;
    • [alert runModal];
    • [alert release;
    Figure 1Alert dialog with an accessory view image: ../Art/alert_accessory.png

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • showsHelp showsHelp Property

    Specifies whether the alert has a help button.

    Declaration

    Swift

    var showsHelp: Bool

    Objective-C

    @property BOOL showsHelp

    Discussion

    Set this property’s value to YEStrue to specify that the alert has a help button, or NOfalse to specify it does not.

    When a user clicks an alert’s help button, the alert delegate (delegate) receives a alertShowHelp: message. If there is no delegate, or if the delegate does not implement that method, or if the delegate returns NOfalse, then the openHelpAnchor:inBook: message is sent to the app’s help manager with a nil book and the anchor specified by the helpAnchor property, if set. An exception is raised if the delegate returns NOfalse and no help anchor is set.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    delegate

  • The alert’s HTML help anchor.

    Declaration

    Swift

    var helpAnchor: String?

    Objective-C

    @property(copy) NSString *helpAnchor

    Discussion

    To provide a help anchor for the alert, set this property to the appropriate string value. To remove the help anchor, set this property’s value to nil.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    showsHelp

  • delegate delegate Property

    The alert’s delegate.

    Declaration

    Swift

    unowned(unsafe) var delegate: NSAlertDelegate?

    Objective-C

    @property(assign) id< NSAlertDelegate > delegate

    Discussion

    To set a delegate for the alert, provide an object conforming to the NSAlertDelegateprotocol to this property. To remove the delegate, set this property’s value to nil.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Runs the alert as an app-modal dialog and returns the constant positionally identifying the button clicked.

    Declaration

    Swift

    func runModal() -> NSModalResponse

    Objective-C

    - (NSModalResponse)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, if necessary in your app, by using the deprecated 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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

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

    Declaration

    Swift

    func beginSheetModalForWindow(_ sheetWindow: NSWindow, completionHandler handler: ((NSModalResponse) -> Void)?)

    Objective-C

    - (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). 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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.9 and later.

    See Also

    – runModal

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

    Deprecation Statement

    Use beginSheetModalForWindow:completionHandler: instead.

    Declaration

    Swift

    func beginSheetModalForWindow(_ window: NSWindow, modalDelegate modalDelegate: AnyObject?, didEndSelector alertDidEndSelector: Selector, contextInfo contextInfo: UnsafeMutablePointer<Void>)

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    Deprecated in OS X v10.10.

  • The alert’s suppression checkbox. (read-only)

    Declaration

    Swift

    var suppressionButton: NSButton? { get }

    Objective-C

    @property(readonly, strong) NSButton *suppressionButton

    Discussion

    If you want to customize an alert’s suppression checkbox, access it via this property and then use the methods of the NSButton class. For example, you can do this to change the suppression checkbox’s default message, or to change its initial selection state (which is “unselected” by default). For a code example, see the showsSuppressionButton property.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Specifies whether the alert includes a suppression checkbox, which you can employ to allow a user to opt out of seeing the alert again.

    Declaration

    Swift

    var showsSuppressionButton: Bool

    Objective-C

    @property BOOL showsSuppressionButton

    Discussion

    The default value of this property is NOfalse, which specifies the absence of a suppression checkbox in the alert. Set the value to YEStrue to show a suppression checkbox in the alert.

    By default, a suppression checkbox has the title, “Do not show this message again.” To customize it, use the checkbox’s title property, as follows:

    • myAlert
    • .suppressionButton.title = @"Do not show this warning again";

    To create an alert that responds to the selection state of the suppression checkbox, use code like that shown in Listing 1. Figure 1 shows the corresponding alert.

    Listing 2Creating an alert with a suppression checkbox
    • NSString *alertSuppressionKey = @"AlertSuppression";
    • NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    • if ([defaults boolForKey: alertSuppressionKey]) {
    • NSLog (@"Alert suppressed");
    • } else {
    • NSAlert *anAlert = [[NSAlert alloc] init];
    • anAlert.messageText = @"Message text.";
    • anAlert.informativeText = @"Informative text.";
    • anAlert.showsSuppressionButton = YES; // Uses default checkbox title
    • [anAlert runModal];
    • if (anAlert.suppressionButton.state == NSOnState) {
    • // Suppress this alert from now on
    • [defaults setBool: YES forKey: alertSuppressionKey];
    • }
    • }
    Figure 2Alert with a suppression checkbox and customized text image: ../Art/alert_suppression.png

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • The alert’s informative text.

    Declaration

    Swift

    var informativeText: String?

    Objective-C

    @property(copy) NSString *informativeText

    Discussion

    The value of this property must not be nil.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    messageText

  • The alert’s message text or title.

    Declaration

    Swift

    var messageText: String?

    Objective-C

    @property(copy) NSString *messageText

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    informativeText

  • icon icon Property

    The custom icon displayed in the alert.

    Declaration

    Swift

    var icon: NSImage!

    Objective-C

    @property(strong) NSImage *icon

    Discussion

    By default, the image used in an alert is the app icon, accessed through the app bundle’s NSApplicationIcon property. If you set this property’s value, your specified custom image is used in place of the app icon.

    If you’ve set a custom alert icon, you can clear it by setting this property’s value to nil, which restores use of the app icon for the alert.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • buttons buttons Property

    The array of response buttons for the alert. (read-only)

    Declaration

    Swift

    var buttons: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *buttons

    Discussion

    The button displayed rightmost in the alert (for a left-to-right language) corresponds to the button at index 0 in this property’s array, and is considered the default button. A user can invoke this button by pressing the Return key.

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Adds a button with a given title to the alert.

    Declaration

    Swift

    func addButtonWithTitle(_ buttonTitle: String) -> NSButton

    Objective-C

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

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    – buttons

  • window window Property

    The app-modal panel or document-modal sheet that corresponds to the alert. (read-only)

    Declaration

    Swift

    var window: AnyObject { get }

    Objective-C

    @property(readonly, strong) id window

    Discussion

    The alert’s window is of type NSPanel. Use this property when you want to dismiss an alert created with the beginSheetModalForWindow:completionHandler: method within that method’s completion handler block.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

Data Types

  • The NSAlert class defines the alert styles used by the alertStyle property.

    Declaration

    Swift

    enum NSAlertStyle : UInt { case WarningAlertStyle case InformationalAlertStyle case CriticalAlertStyle }

    Objective-C

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

    Constants

    • WarningAlertStyle

      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.

    • InformationalAlertStyle

      NSInformationalAlertStyle

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

      Available in OS X v10.3 and later.

    • CriticalAlertStyle

      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.

    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.

    Import Statement

    Objective-C

    @import AppKit;

    Swift

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • 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).

    Declaration

    Swift

    var NSAlertFirstButtonReturn: Int { get } var NSAlertSecondButtonReturn: Int { get } var NSAlertThirdButtonReturn: Int { get }

    Objective-C

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

    Constants

    • NSAlertFirstButtonReturn

      NSAlertFirstButtonReturn

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

      Available in OS X v10.3 and later.

    • NSAlertSecondButtonReturn

      NSAlertSecondButtonReturn

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

      Available in OS X v10.3 and later.

    • NSAlertThirdButtonReturn

      NSAlertThirdButtonReturn

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

      Available in OS X v10.3 and later.

    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.