How to create an Alert View in Cocoa

Much like a UIAlertView, you can run an NSAlert on Mac like this:

// run a modal alert
NSAlert *alert = [[NSAlert alloc]init];
[alert addButtonWithTitle:@"Excellent"];
[alert setMessageText:@"This is your message."];
[alert runModal];

Or, if you prefer a much simpler one-liner you can use NSRunAlertPanel:

NSRunAlertPanel(@"Title", @"This is your message.", @"OK", nil, nil);

Your App Icon will be displayed in the window. Here’s an example:

Screen Shot 2014-05-01 at 18.20.43

The result will be the same: a separate modal window is brought up, waiting for the user to dismiss it with any of the buttons. The latter method will return an NSInteger to indicate which button was pressed.

Alert Sheets

Instead of the Alert Panel, we can also run an Alert Sheet. The functionality is the same, but instead of being a floating window the Alert Sheet is attached to your main application window. This is what it looks like:

Screen Shot 2014-05-03 at 10.10.31

You can create Alert Sheets like this:

NSAlert *alertSheet = [NSAlert alertWithMessageText:@"Title goes here." defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"And your message goes here goes here. Nice."];
    [alertSheet beginSheetModalForWindow:self.window modalDelegate:nil didEndSelector:nil contextInfo:nil];

The above method relies on a delegate to be called so you can evaluate which button was clicked. Alternatively – if you prefer blocks and evaluate the result right there and then – you can call the Alert Sheet with

[alertSheet beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {        
    // check returnCode here

Leave a Reply