51

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 5

85

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:.

enter image description here enter image description here

3
  • I'll be adding my button in code, but thanks for the alternative solution as well. Commented Aug 9, 2011 at 7:13
  • Just curious, what IDE is this answer referring to?
    – Mythics
    Commented Jul 25, 2014 at 18:03
  • 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
23
[[NSApplication sharedApplication] terminate:self];
2
  • 1
    What is the difference between this and [NSApp terminate:self];?
    – 11684
    Commented Feb 26, 2013 at 16:23
  • 12
    There is no difference, NSApp is the same as [NSApplication sharedApplication].
    – omz
    Commented Feb 26, 2013 at 16:26
7

Try the following:

[NSApp terminate: nil];
1
  • This is the answer that worked for me. Using self as the argument caused an exception when invoking this from a worker thread, but using nil worked as expected. Commented Aug 19, 2024 at 21:57
4

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];
2
  • 1
    What else as NSWindow instances could the windows property of NSApplication return?
    – vadian
    Commented May 27, 2016 at 7:19
  • @vadian Oh yes, you are right windows is only return NSWindow. I will edit code
    – larva
    Commented May 27, 2016 at 7:23
3

Written in Swift:

NSApp.terminate(self)

or

NSApplication.shared.terminate(self)

Not the answer you're looking for? Browse other questions tagged or ask your own question.