mike chambers | about

Reopening an NSWindow once it has been closed

Tuesday, December 2, 2008

Unlike on Windows, the convention on Mac is that when the main application Window is closed, the application does not exit (although there are exception to this). If you are working on a Document based application, the functionality to open a new window is built in (just open a new document), however for a non-Document based Cocoa application, you have to implement this functionality yourself, which is pretty simple. First, you have to tell the window (NSWindow) to only hide itself when it is closed, and not also release itself.

-(void)awakeFromNib
{
	[mainWindow setReleasedWhenClosed:FALSE];
}

You then need to create an IBAction that is hooked up to a menu item to reopen the window once it is closed. I use Window > Main Window (I cant find a convention for it). You can re-open the window by calling makeKeyAndOrderFront.

-(IBAction)handleNewMainWindowMenu:(NSMenuItem *)sender
{
	[mainWindow makeKeyAndOrderFront:self];
}

This will un-hide or re-open the main application window. If you want to disable the Main Window NSMenuItem when the window is open (and enable when it is not open) then you can check the windows visibility in the menu’s validateMenuItem delegate method (hooked up as the delegate to the NSMenu that contains the Main Window’s NSMenuItem:

#define MAIN_WINDOW_MENU_TAG 150
- (BOOL)validateMenuItem:(NSMenuItem *)item
{
	//check to see if the Main Menu NSMenuItem is
	//being validcated
	if([item tag] == MAIN_WINDOW_MENU_TAG)
	{
		return ![mainWindow isVisible];
	}
	
	return TRUE;
}

Note that I set the tag for the NSMenuItem to 150. Now, when the user closes the main application window, they can re-open it by selecting Window > Main Window.

twitter github flickr behance