Search code examples
objective-cmacosquitnsalert

NSAlertPanel not working when Application is quitting


Im trying to allow the user to decide whether to quit the application or not and Ive been trying to implement it using this:

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
int answer = NSRunAlertPanel(@"Quit", @"Are you sure?", @"Quit", @"Cancel", nil);
if (answer == NSAlertDefaultReturn) { return NSTerminateNow;
} else { return NSTerminateCancel;
}
}

I have placed this in my AppDelegate.m and linked the delegate to my main window in interface builder. When i debug and run the application in Xcode, and press the close button, the app window closes but the alert panel does not pop up..

Am i doing something wrong? thank you for your help!! I am new here and I hope someone can help me with this.. Thank you so much!


Solution

  • By default closing a window will not quit the application, thus not triggering your alert panel. To make the application quit and show your alert when the user closes the window just add this to the delegate:

    - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)aApplication {
         return YES;
    }