XCode: NSAlert Message Dialog Example Code

An often used xcode method for cocoa or iOS apps is NSAlert . It is very useful to display an alert or a short message to the user. Here you get an example code for copying into xcode source code. At first create the alert view with all needed buttons and text. To parameter didEndSelector you write the method, wich is called if alert is finshed by clicking at one of the defined buttons.

NSAlert *alert = [[NSAlert alloc]init];
[alert setAlertStyle:NSInformationalAlertStyle];
[alert setMessageText:@"myMessage"];
[alert addButtonWithTitle:@"Cancel"];
[alert addButtonWithTitle:@"Okay"];
[alert beginSheetModalForWindow:_window modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];

At second you need the alertDidEnd-method. The method should be in the same class where you alloc and init the alert.

- (void) alertDidEnd:(NSAlert *)a returnCode:(NSInteger)rc contextInfo:(void *)ci {
    switch(rc) {
        case NSAlertFirstButtonReturn:
            // First Button pressed...in our case the Cancel-Button
            // do whatever you want hier
        case NSAlertSecondButtonReturn:
            // Second Button pressed ... in our case the Okay-Button
            // do something here


comments powered by Disqus

Copyright Dunkel & Iwer GbR | Datenschutzerklärung | Impressum