| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/AppKit.framework |
| Availability | Available in Mac OS X v10.3 and later. |
| Declared in | NSAlert.h |
| Companion guides | |
| Related sample code |
You use an NSAlert object to display 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, invoke the beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo: 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”
Note:
The NSAlert class, which was introduced in Mac OS X v10.3, supersedes the functional Application Kit API for displaying alerts (NSRunAlertPanel, NSBeginAlertSheet, and so on). The former API is still supported, but you should use the NSAlert class for your application’s alert dialogs.
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.
An alert also has a delegate; see “Displaying Help.”
The NSAlert class is not designed for subclassing.
+ alertWithError:
+ alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:
– layout
– alertStyle
– setAlertStyle:
– accessoryView
– setAccessoryView:
– showsHelp
– setShowsHelp:
– helpAnchor
– setHelpAnchor:
– delegate
– setDelegate:
– runModal
– beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:
– suppressionButton
– showsSuppressionButton
– setShowsSuppressionButton:
An alert’s delegate is responsible for displaying help for the alert.
– alertShowHelp: delegate method
Returns an alert initialized from information in an error object.
+ (NSAlert *)alertWithError:(NSError *)error
Error information to display.
Initialized alert.
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.
NSAlert.hCreates an alert compatible with alerts created using the NSRunAlertPanel function for display as a warning-style alert.
+ (NSAlert *)alertWithMessageText:(NSString *)messageTitle defaultButton:(NSString *)defaultButtonTitle alternateButton:(NSString *)alternateButtonTitle otherButton:(NSString *)otherButtonTitle informativeTextWithFormat:(NSString *)informativeText, ...
Title of the alert. When nil or an empty string, a default localized title is used (“Alert” in English).
Title for the default button. When nil or an empty string, a default localized button title (“OK” in English) is used.
Title for the alternate button. When nil, the alternate button is not created.
Title for the other button. When nil, the other button is not created.
Informative text, optional. 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.
Initialized alert.
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.
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 “Constants.”
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.
NSAlert.hReturns the receiver’s accessory view.
- (NSView *)accessoryView
The alert’s accessory view.
NSAlert.hAdds a button with a given title to the receiver.
- (NSButton *)addButtonWithTitle:(NSString *)buttonTitle
Title of the button to add to the alert. Must not be nil.
Button added to the alert.
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 is 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.
NSAlert.hReturns the NSAlertStyle constant identifying the receiver’s alert style.
- (NSAlertStyle)alertStyle
Alert style for the alert. See NSAlertStyle for the list of alert style constants.
NSAlert.hRuns the receiver modally as an alert sheet attached to a specified window.
- (void)beginSheetModalForWindow:(NSWindow *)window modalDelegate:(id)modalDelegate didEndSelector:(SEL)alertDidEndSelector contextInfo:(void *)contextInfo
The parent window for the sheet.
The delegate for the modal-dialog session.
Message the alert sends to modalDelegate after the user responds but before the sheet is dismissed.
Contextual data passed to modalDelegate in didEndSelector message.
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:(int)returnCode contextInfo:(void *)contextInfo; |
where alert is the NSAlert object, returnCode specifies which button the user pressed, 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.
When you use alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: to create an alert, these are the constants 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.”
NSAlert.hReturns the receiver’s buttons.
- (NSArray *)buttons
The alert’s buttons. The rightmost button is at index 0.
NSAlert.hReturns the receiver’s delegate.
- (id)delegate
The alert’s delegate.
NSAlert.hReturns the receiver’s HTML help anchor.
- (NSString *)helpAnchor
The alert’s help anchor. It’s nil when the alert has no help anchor.
NSAlert.hReturns the icon displayed in the receiver.
- (NSImage *)icon
The alert’s icon.
The default image is the application icon (NSApplicationIcon application property).
NSAlert.hReturns the receiver’s informative text.
- (NSString *)informativeText
The alert’s informative text.
NSAlert.hSpecifies that the receiver must do immediate layout instead of lazily just before display.
- (void)layout
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.
Note: The standard alert layout is subject to change in future system software versions. Therefore, if you rely on custom alert layout, you should make sure your layouts work as expected in future releases of Mac OS.
NSAlert.hReturns the receiver’s message text (or title).
- (NSString *)messageText
The alert’s message text.
NSAlert.hRuns the receiver as an application-modal dialog and returns the constant positionally identifying the button clicked.
- (NSInteger)runModal
Response to the alert. See this method’s “Special Considerations” section for details.
You can create the alert either through the standard allocate–initialize procedure or by using the compatibility method alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:.
When you use alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: to create an alert, these are the constants 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.”
NSAlert.hSets the receiver’s accessory view.
- (void)setAccessoryView:(NSView *)accessoryView
View that is to be the alert’s accessory view.
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 new]; |
[alert setInformativeText: @"Informative text"]; |
[alert setMessageText: @"Message text"]; |
[alert setAccessoryView:accessory]; |
[alert runModal]; |
NSAlert.hSets the alert style of the receiver.
- (void)setAlertStyle:(NSAlertStyle)style
Alert style for the alert. Indicates the severity level of the alert. See NSAlertStyle for the list of alert style constants.
NSAlert.hSets the receiver’s delegate.
- (void)setDelegate:(id)delegate
Delegate for the alert. nil removes the delegate.
NSAlert.hAssociates the receiver to a given anchor.
- (void)setHelpAnchor:(NSString *)anchor
Anchor to associate with the alert. nil removes the associated help anchor.
NSAlert.hSets the icon to be displayed in the alert to a given icon.
- (void)setIcon:(NSImage *)icon
Icon for the alert. nil restores the application icon.
By default, the image is the application icon, accessed via the application bundle’s NSApplicationIcon property.
NSAlert.hSets the receiver’s informative text to a given text.
- (void)setInformativeText:(NSString *)informativeText
Informative text for the alert.
NSAlert.hSets the receiver’s message text, or title, to a given text.
- (void)setMessageText:(NSString *)messageText
Message text for the alert.
NSAlert.hSpecifies whether the receiver has a help button.
- (void)setShowsHelp:(BOOL)showsHelp
YES for a help button, NO for no help button.
When the help button is pressed, 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.
NSAlert.hSpecifies whether the receiver includes a suppression checkbox.
- (void)setShowsSuppressionButton:(BOOL)showButton
When YES the alert includes the suppression checkbox.
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 (with the default suppression-checkbox title) 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 new]; |
[alert setInformativeText: @"Informative text"]; |
[alert setMessageText: @"Message text"]; |
[alert setShowsSuppressionButton:YES]; |
[alert runModal]; |
if ([[alert suppressionButton] state] == NSOnState) { |
// Suppress this alert from now on. |
[defaults setBool:YES forKey:exampleAlertSuppress]; |
} |
} |
NSAlert.hIndicates whether the receiver has a help button.
- (BOOL)showsHelp
YES if the alert has a help button, NO otherwise.
NSAlert.hIndicates whether the receiver shows a suppression button.
- (BOOL)showsSuppressionButton
YES when the alert shows a suppression button, NO otherwise. The default is NO.
NSAlert.hReturns the receiver’s suppression checkbox.
- (NSButton *)suppressionButton
The alert’s suppression button.
You can 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.
NSAlert.hProvides the application-modal panel associated with the receiver.
- (id)window
The receiver’s associated NSPanel object.
This method is useful when you want to dismiss an alert created with beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo: within the method identified by the didEndSelector: parameter.
NSAlert.hSent to the delegate when the user clicks the alert’s help button. The delegate causes help to be displayed for an alert, directly or indirectly.
- (BOOL)alertShowHelp:(NSAlert *)alert
YES when the delegate displayed help directly, NO otherwise. When NO and the alert has a help anchor (setHelpAnchor:), the application’s help manager displays help using the help anchor.
The delegate implements this method only to override the help-anchor lookup behavior.
NSAlert.hThe NSAlert class defines these alert styles.
enum {
NSWarningAlertStyle = 0,
NSInformationalAlertStyle = 1,
NSCriticalAlertStyle = 2
};
typedef NSUInteger NSAlertStyle;
NSWarningAlertStyleAn 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 Mac OS X v10.3 and later.
Declared in NSAlert.h.
NSInformationalAlertStyleAn alert used to inform the user about a current or impending event.
Available in Mac OS X v10.3 and later.
Declared in NSAlert.h.
NSCriticalAlertStyleReserved 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 Mac OS X v10.3 and later.
Declared in NSAlert.h.
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 Apple Human Interface Guidelines.
NSAlert.hAn 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
};
NSAlertFirstButtonReturnThe user clicked the first (rightmost) button on the dialog or sheet.
Available in Mac OS X v10.3 and later.
Declared in NSAlert.h.
NSAlertSecondButtonReturnThe user clicked the second button from the right edge of the dialog or sheet.
Available in Mac OS X v10.3 and later.
Declared in NSAlert.h.
NSAlertThirdButtonReturnThe user clicked the third button from the right edge of the dialog or sheet.
Available in Mac OS X v10.3 and later.
Declared in NSAlert.h.
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.
NSAlert.h
Last updated: 2007-04-25