I need to add a quit-button to my application that runs from the menubar in mac. How do I programmatically quit an application in mac?
5 Answers
There is a simpler form to quit from code:
[NSApp terminate:self];
But as you're adding a button, all you have to do is to control drag from your button to the Application icon and connect the method terminate:
.
-
I'll be adding my button in code, but thanks for the alternative solution as well. Commented Aug 9, 2011 at 7:13
-
-
Note that in newer versions of Xcode you should create a outlet between the button and the File's Owner placeholder, instead of the application. Commented Feb 6, 2018 at 16:34
[[NSApplication sharedApplication] terminate:self];
Try the following:
[NSApp terminate: nil];
-
This is the answer that worked for me. Using
self
as the argument caused an exception when invoking this from a worker thread, but usingnil
worked as expected. Commented Aug 19, 2024 at 21:57
In some case you cannot close app when call [NSApp terminate:self];
. Like when showing NSAlert as sheet on the doc window (NSAlert -beginSheetModalForWindow:completionHandler:
) ...
You can close all window and alert before call terminate, like following code:
for (NSWindow *window in [NSApplication sharedApplication].windows) {
[window close];
}
[NSApp terminate:self];