NSAlert – Alerts in Cocoa, Objective-C

Alerts in Cocoa, Objective C

Alerts are key to any application.
Some of the usages of an application alerts are as follows

  • To display an informative message
  • To take confirmation from user before continuing with a transaction
  • As a success or failure response to the end user.
  • Giving the user more than one option to take a action (save, dont-save, cancel etc).

An NSAlert object displays an application model or as a sheet attached to a document window.

Sample 1: Showing a simple alert message with a warning alert style

NSAlert1

 

-(void)showSimpleAlert
{
 NSAlert *alert = [[NSAlert alloc] init];
 [alert addButtonWithTitle:@"Continue"];
 [alert addButtonWithTitle:@"Cancel"];
 [alert setMessageText:@"Alert"];
 [alert setInformativeText:@“NSWarningAlertStyle \r Do you want to continue with delete of selected records"];
 [alert setAlertStyle:NSWarningAlertStyle];
 [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
 /*
 The following options are deprecated in 10.9. Use NSAlertFirstButtonReturn instead
 NSAlertDefaultReturn = 1,
 NSAlertAlternateReturn = 0,
 NSAlertOtherReturn = -1,
 NSAlertErrorReturn = -2
 NSOKButton = 1, // NSModalResponseOK should be used 
 NSCancelButton = 0 // NSModalResponseCancel should be used
 */
 if (returnCode == NSOKButton)
 {
 NSLog(@"(returnCode == NSOKButton)");
 }
 else if (returnCode == NSCancelButton)
 {
 NSLog(@"(returnCode == NSCancelButton)");
 }
 else if(returnCode == NSAlertFirstButtonReturn)
 {
 NSLog(@"if (returnCode == NSAlertFirstButtonReturn)");
 }
 else if (returnCode == NSAlertSecondButtonReturn)
 {
 NSLog(@"else if (returnCode == NSAlertSecondButtonReturn)");
 }
 else if (returnCode == NSAlertThirdButtonReturn)
 {
 NSLog(@"else if (returnCode == NSAlertThirdButtonReturn)");
 }
 else
 {
 NSLog(@"All Other return code %d",returnCode);
 }
}

 

Sample 2: Showing a simple alert message with a critical alert style

NSAlert2

-(void)showSimpleCriticalAlert
{
 NSAlert *alert = [[NSAlert alloc] init];
 [alert addButtonWithTitle:@"OK"];
 [alert setMessageText:@"Alert"];
 [alert setInformativeText:@"NSCriticalAlertStyle\rPlease enter a valid email id."];
 [alert setAlertStyle:NSCriticalAlertStyle];
 [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

Sample 3: Showing a simple alert message with a informational alert style

NSAlert3

-(void)showSimpleInformationalAlert
{
 NSAlert *alert = [[NSAlert alloc] init];
 [alert addButtonWithTitle:@"OK"];
 [alert setMessageText:@"Alert"];
 [alert setInformativeText:@"NSInformationalAlertStyle \r Please enter a valid email id."];
 [alert setAlertStyle:NSInformationalAlertStyle];
 [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

Sample 4: Creating an Alert with more than 3 buttons

NSAlert4

-(void)showSimpleAlertSheetWithMultipleButtons
{
 NSAlert *alert = [[NSAlert alloc] init];
 [alert addButtonWithTitle:@"Button One"]; //will generate a return code of 1000
 [alert addButtonWithTitle:@"Button Two"]; //will generate a return code of 1001
 [alert addButtonWithTitle:@"Button Three"]; //will generate a return code of 1002
 [alert addButtonWithTitle:@"Button Four”]; //will generate a return code of 1003
 [alert addButtonWithTitle:@"Button Five"]; //will generate a return code of 1004
 [alert setMessageText:@"Alert"];
 [alert setInformativeText:@"This is a five buttons alert message"];
 [alert setAlertStyle:NSInformationalAlertStyle];
 [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

Sample 5: Creating an Alert using Factory Methods

NSAlert5

-(void)showAlertFromFactoryMethod
{
 NSAlert *alert = [NSAlert alertWithMessageText:@"Delete the record?"
 defaultButton:@"OK" 
 alternateButton:@"Cancel" 
 otherButton:nil
 informativeTextWithFormat:@"Deleted records cannot be restored."];
[alert beginSheetModalForWindow:[self window] 
modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) 
contextInfo:nil];
}

Sample 6: Creating an Alert using Functional API

NSAlert6

-(void)showAlertUsingFunctionalAPI
{
 NSBeginAlertSheet(
 @"Do you really want to delete the selected rows?", // sheet message
 @"Delete", // default button label
 nil, // no third button
 @"Cancel", // other button label
 [self window], // window , the sheet is attached to.
 self, // The delegate for the alert
 @selector(sheetDidEndShouldDelete:returnCode:contextInfo:), 
 NULL, // no need for did-dismiss selector
 nil, // context info
 @"There is no undo for this operation.");
//didEndSelector
//A selector for a method implemented by modalDelegate. This method is sent when the modal session is ended, but before the sheet is dismissed.
//didDismissSelector
//A selector for a method implemented by modalDelegate. This method is sent after the sheet is dismissed in the event
}

Sample 7: Creating an Alert with Help button in the alert

NSAlert7

-(void)showAlertWithHelp
{
 NSAlert *alert = [[NSAlert alloc] init];
 [alert addButtonWithTitle:@"OK"];
 [alert addButtonWithTitle:@"Cancel"];
 [alert setMessageText:@"Alert"];
 [alert setInformativeText:@"Please enter an email id."];
 [alert setAlertStyle:NSWarningAlertStyle];
 [alert setShowsHelp:YES];
 [alert setDelegate:self];
 [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
- (BOOL)alertShowHelp:(NSAlert *)alert {
 NSLog(@"%s",__func__);
 NSString *path = [[NSBundle mainBundle] pathForResource:@"Credits" ofType:@"rtf"];
 BOOL flag = [[NSWorkspace sharedWorkspace] openFile:path];
 return flag;
}
-(void)testDeprecatedAlertMethods
{
 NSInteger integ = NSRunAlertPanel(@"Alert",
 @"Message Format",
 @"OK",
 @"ALTERNATE BUTTON",
 @"OTHER BUTTON");
 //The Flow stops here and the next line is not executed till the time user clicks on a button on the alert panel
 NSInteger criticalInteg = NSRunCriticalAlertPanel(
 @"Critical Alert",
 @"Message Format",
 @"DEFAULT BUTTON",
 @"ALTERNATE BUTTON",
 @"OTHER BUTTON");
 NSLog(@"integ %ld",integ);
 NSLog(@"criticalInteg %ld",criticalInteg);
}

 

Sample 8: Creating a custom alert sheet and positioning it at a particular point

NSAlert8

-(void)showCustomSheet
{
 {
 if (!_customSheet)
 //Check the myCustomSheet instance variable to make sure the custom sheet does not already exist.
 [NSBundle loadNibNamed: @"CustomSheet" owner: self];
 [NSApp beginSheet: self.customSheet
 modalForWindow: self.window
 modalDelegate: self
 didEndSelector: @selector(didEndSheet:returnCode:contextInfo:)
 contextInfo: nil];
 // Sheet is up here.
 }
}
- (IBAction)closeMyCustomSheet: (id)sender
{
 [NSApp endSheet:_customSheet];
}
- (void)didEndSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
 NSLog(@"%s",__func__);
 NSLog(@"return Code %d",returnCode);
 [sheet orderOut:self];
}
The below method is required to have a different point to show the alert from
- (NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet
 usingRect:(NSRect)rect
{
 NSLog(@"%s",__func__);
 if (sheet == self.customSheet)
 {
 NSLog(@"if block");
 NSRect fieldRect = [self.showAlertButton frame];
 fieldRect.size.height = 0;
 return fieldRect;
 }
 else
 {
 NSLog(@"else block");
 return rect;
 }
}

 

Sample 9: Creating a alert sheet with additional information displayed in an accessory view

NSAlert9

 

-(void)showAlertWithDetailedInformation:(NSString *)detailedInformation
{
 NSTextView *accessory = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,200,50)];
 NSFont *font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
 NSDictionary *textAttributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
 [accessory insertText:[[NSAttributedString alloc] initWithString:detailedInformation
 attributes:textAttributes]];
 [accessory setEditable:NO];
 [accessory setDrawsBackground:YES];
 [accessory setBackgroundColor:[NSColor cyanColor]];
 NSAlert *alert = [[NSAlert alloc] init];
 [alert setMessageText:@"Message text."];
 [alert setInformativeText:@"Informative text."];
 [alert setAccessoryView:accessory];
 [alert runModal]; 
}

NSAlerts – Download the PDF

Reference: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSAlert_Class/Reference/Reference.html

 

 

Posted in Cocoa, Objective C Tagged with: , , , , , ,
2 comments on “NSAlert – Alerts in Cocoa, Objective-C
  1. ingconti says:

    a switch is more clear:

    switch (returnCode) {
    case NSOKButton:
    break;
    ….
    default:
    break;
    }

  2. ingconti says:

    PS: for yosemite you should use:

    switch (returnCode) {
    case NSModalResponseOK:
    break;
    case NSModalResponseCancel:
    break;
    default:
    break;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news