Search code examples
objective-cmacoscocoa

Can create NSAlert without button in Cocoa


I'm a newbie in Cocoa. I want to create a messagebox in cocoa same in iOS without any button. Messagebox auto close after NSTimer. I used below code but it always add OK button.

alert = [[[NSAlert alloc] init] autorelease];
// [alert addButtonWithTitle: @"OK"];
[alert setMessageText: @"Attention!!! This a critical Alert."];
[alert setInformativeText:@"Scanning..."];
[alert setAlertStyle: NSInformationalAlertStyle];

NSTimer *myTimer = [NSTimer timerWithTimeInterval: 17.0
                                           target:self
                                         selector: @selector(killWindow:) userInfo:nil
                                                             repeats:NO];

[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSModalPanelRunLoopMode];

int choice = 0;
choice = [alert runModal];
if(choice != 0)
    [myTimer invalidate];

KillWindow function:

-(void) killWindow: (NSTimer *) theTimer
{
    NSLog(@"killWindow");
    [[alert window] close];
}

And when alert close, my app can not click any button or interaction?


Solution

  • NSAlert is designed to be used for application or window-modal display of a message with buttons for user dismissal. It is not designed for displaying windows with no buttons; you should not use it this way.

    You should use a custom NSWindow/NSPanel. If you want it to block the window/application, then you will need to run your own modal session. Stop the modal session from your timer callback with abortModal, in addition to closing the window as you do above. This explains why you aren't getting any further events when the alert closes — the modal session is still running.

    See How Modal Windows Work for more information.