Mac Developer Library

Developer

AppKit Framework Reference NSAlert Class Reference

Options
Deployment Target:

On This Page
Language:

NSAlert

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

Inheritance


Conforms To


Import Statement


import AppKit @import AppKit;

Availability


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

    Declaration

    Objective-C

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

    Import Statement

  • 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

    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.

    Import Statement

    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 in String Programming Guide.

    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.

    Import Statement

    Availability

    Available in OS X v10.3 and later.

    Deprecated in OS X v10.10.

  • Specifies that the receiver 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

    import AppKit

    Availability

    Available in OS X v10.5 and later.

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

    Declaration

    Swift

    var alertStyle: NSAlertStyle

    Objective-C

    @property NSAlertStyle alertStyle

    Return Value

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Sets the alert style of the receiver.

    Declaration

    Swift

    var alertStyle: NSAlertStyle

    Objective-C

    @property NSAlertStyle alertStyle

    Parameters

    style

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    – alertStyle

  • Returns the receiver’s accessory view.

    Declaration

    Swift

    var accessoryView: NSView?

    Objective-C

    @property(strong) NSView *accessoryView

    Return Value

    The alert’s accessory view.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Sets the receiver’s accessory view.

    Declaration

    Swift

    var accessoryView: NSView?

    Objective-C

    @property(strong) 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 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 setMessageText:@"Message text."];
    • [alert setInformativeText:@"Informative text."];
    • [alert setAccessoryView:accessory];
    • [alert runModal];
    • [alert release;
    Figure 1Alert dialog with an accessory view image: ../Art/alert_accessory.png

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Indicates whether the receiver has a help button.

    Declaration

    Swift

    var showsHelp: Bool

    Objective-C

    @property BOOL showsHelp

    Return Value

    YEStrue if the alert has a help button, NOfalse otherwise.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Specifies whether the receiver has a help button.

    Declaration

    Swift

    var showsHelp: Bool

    Objective-C

    @property BOOL showsHelp

    Parameters

    showsHelp

    YEStrue for a help button, NOfalse 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 NOfalse, 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 NOfalse and no help anchor is set.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Returns the receiver’s HTML help anchor.

    Declaration

    Swift

    var helpAnchor: String?

    Objective-C

    @property(copy) NSString *helpAnchor

    Return Value

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Associates the receiver to a given anchor.

    Declaration

    Swift

    var helpAnchor: String?

    Objective-C

    @property(copy) NSString *helpAnchor

    Parameters

    anchor

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Returns the receiver’s delegate.

    Declaration

    Swift

    unowned(unsafe) var delegate: NSAlertDelegate?

    Objective-C

    @property(assign) id<NSAlertDelegate> delegate

    Return Value

    The alert’s delegate.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

  • Sets the receiver’s delegate.

    Declaration

    Swift

    unowned(unsafe) var delegate: NSAlertDelegate?

    Objective-C

    @property(assign) id<NSAlertDelegate> delegate

    Parameters

    delegate

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    – delegate

  • Runs the receiver as an application-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 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.

    Import Statement

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.9 and later.

    See Also

    – runModal

  • Runs the receiver 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

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    Deprecated in OS X v10.10.

  • Returns the receiver’s suppression checkbox.

    Declaration

    Swift

    var suppressionButton: NSButton? { get }

    Objective-C

    @property(readonly, strong) 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.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Indicates whether the receiver shows a suppression button.

    Declaration

    Swift

    var showsSuppressionButton: Bool

    Objective-C

    @property BOOL showsSuppressionButton

    Return Value

    YEStrue when the alert shows a suppression button, NOfalse otherwise. The default is NOfalse.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Specifies whether the receiver includes a suppression checkbox.

    Declaration

    Swift

    var showsSuppressionButton: Bool

    Objective-C

    @property BOOL showsSuppressionButton

    Parameters

    showButton

    When YEStrue 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 2Creating 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 2Alert dialog with a suppression checkbox image: ../Art/alert_suppression.png

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.5 and later.

  • Returns the icon displayed in the receiver.

    Declaration

    Swift

    var icon: NSImage!

    Objective-C

    @property(strong) NSImage *icon

    Return Value

    The alert’s icon.

    Discussion

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    – setIcon:

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

    Declaration

    Swift

    var icon: NSImage!

    Objective-C

    @property(strong) 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.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    – icon

  • Returns the receiver’s buttons.

    Declaration

    Swift

    var buttons: [AnyObject] { get }

    Objective-C

    @property(readonly, copy) NSArray *buttons

    Return Value

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

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

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

    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

    import AppKit

    Availability

    Available in OS X v10.3 and later.

    See Also

    – buttons

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

    Declaration

    Swift

    var window: AnyObject { get }

    Objective-C

    @property(readonly, strong) 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.

    Import Statement

    import AppKit

    Availability

    Available in OS X v10.3 and later.

Data Types

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

    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

    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.

    Import Statement