Cocoa – Windows close button quites App?

Discussion in 'Mac Programming' started by netytan, Jan 15, 2005.

  1. macrumors 6502

    netytan

    Joined:
    May 23, 2004
    #1
    Heys,

    This is probably so easy, as easy as checking a box in IB even. Anyway, I would like a way to make my Cocoa applications close button (the red button in the top left) quit the application – like with System Preferences :cool:.

    Thanks all,

    Mark.
     
  2. macrumors member

    Joined:
    Oct 7, 2004
    #2
    So what you need to do first is have the window you want to close be connected to an IBOutlet in the nib. For this example i connected the window to an outlet named "mainWindow".

    The code to add is:
    Code:
    - (void)awakeFromNib {
            [mainWindow setDelegate:self];
    }
    
    - (void)windowWillClose:(NSNotification *)aNotification {
    	[NSApp terminate:self];
    }
    what this code does is overwrite the window closing action and tells it to quit instead. you do not need to add the "windowWillClose:" method to your header file.
     
  3. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #3
    Or use a delegate to the NSApplication object that returns YES to
    Code:
    - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
    You can set any object to be the NSApplication object by putting something like
    Code:
    [NSApp setDelegate:self];
    in awakeFromNib.

    Documentation here
     
  4. thread starter macrumors 6502

    netytan

    Joined:
    May 23, 2004
    #4
    Thanks a lot :) got it working fine with both methods, though I did the delegation in Interface Builder rather than programatically (just seemed like the right thing to do ;)).

    Anyway, Is there a way to set NSApp's delegate from Interface Builder too or not?

    Thanks again guys,

    Mark.
     
  5. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    As you are not in a document based app the File's Owner is the NSApplication object. You can use this to set the delegate.

    Edit: I think this is always true for the MainMenu.nib file. Anyone?
     
  6. thread starter macrumors 6502

    netytan

    Joined:
    May 23, 2004
    #6
    Ta Robbie :).
     
  7. macrumors newbie

    Joined:
    Feb 3, 2010
    #7
    Thanks a lot for this topic, it works! :)
     
  8. macrumors 68000

    Sydde

    Joined:
    Aug 17, 2009
    #8
    Yes.
     

Share This Page