Close window when stop application(stop modal window)

By default, if closes application main window, application still runs.

When closing modal window, application cannot recognise closing modal window, and keep modal status.

That’s a problem.

Steps are same to prevent running modal window and main window.

  1. Implements NSWindowDelegate
  2. Override -(void)windowWillClose:(NSNotification *)notification

Stop modal status

We need to assign Window delegate to File’s owner using XCode.

Click window in InterfaceBuilder and point delegate and drag drop to File’s owner.

filesowner

Prepare was done.

Header

@interface MainWindowController : NSWindowController<NSWindowDelegate>
@end

Implements NSWindowDelegate

Code

-(void)windowWillClose:(NSNotification *)notification
{
    [[NSApplication sharedApplication] stopModalWithCode:1];
}

Override

Terminate program when closing application

AppDelegate.h

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
@end

AppDelegate.m

Override windowWillClose

#pragma mark - 
#pragma mark NSWindowDelegate close event
-(void)windowWillClose:(NSNotification *)notification
{
    [NSApp terminate:self];
}