DevCompany
DevCompany

Reputation: 699

Completely close an OS X application with window close button

I need completely close my application when a user closes the document window using the applications at runtime.

Currently when they click the window, the application stays open and is displaying its menu bar. I read this article for iOS and to add an entry into the plist file: http://developer.appcelerator.com/question/40081/ios4---make-app-not-run-in-background

What is the easiest way for me to close the entire app when a user closes the document window?

Upvotes: 24

Views: 11360

Answers (3)

mipadi
mipadi

Reputation: 410662

Is this a Mac app? If so, have your NSApp delegate implement applicationShouldTerminateAfterLastWindowClosed::

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

Using Swift, it would be:

func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
     return true
}

Upvotes: 56

Erfan
Erfan

Reputation: 1304

Add the NSWindowDelegate in YourWindowController.h file and then add the following method in YourWindowController.m file:

-(void)windowWillClose:(NSNotification *)notification
{
    // You can use either of the following lines:
    [[NSApplication sharedApplication] terminate:nil];

    // OR
    exit(0);
}

You will need to use the NSWindowDelegate for all your windows.

Upvotes: 1

Liftoff
Liftoff

Reputation: 25392

When the button is pressed:

[NSApp terminate:self];

Upvotes: 6

Related Questions