Quit application after last window closes
-
01-01-2021 - |
Question
I want to close my application when the last main window closes. I cannot use applicationShouldTerminateAfterLastWindowClosed:
for the following reasons:
1. Before showing the main window, one confirmation window is displayed and when this window is closed, the application should not quit.
2. The application should quit after closing the main window even if there is any help window still open.
Solution
What you need to do is set you controlling class as the delegate of your main window, and then using NSNotificationCenter add an observer with the NSWindowWillCloseNotification with yourWindow being the object. So like this
NSNotificationCenter *c = [NSNotificationCenter defaultCenter];
[c addObserver:self selector:@selector(yourSelector) name:NSWindowWillCloseNotification object:yourWindow];
Now, the method yourSelector will be called when the main window is close, so in that method just have something like exit(0);
For more info go here and look at windowWillClose
OTHER TIPS
You may still use applicationShouldTerminateAfterLastWindowClosed:
Write it to return NO
until the moment you first show the main window. Make it return YES
from then onwards.
Instances of NSPanel don't count towards open windows. Thus this will work if your help window is a NSPanel.