What's the correct way to reopen a window on OSX?

cocoa, macos, nsapplication, nswindow

Solution

Generally, I find that working with `NSWindowControllers` makes dealing with windows much simpler. In your case, your App Delegate wouldn't own the window directly, but would instead own the `NSWindowController` that owns the window.

To do this, you'd create a new `NSWindowController` subclass (with a xib for the user interface), and the migrate your window from the MainMenu.xib into your new WindowController.xib. Hook things up, and then you're ready to go. (also, make sure the "Visible at launch" checkbox on your window is unchecked)

From your app delegate, you'll then just create a new instance of the window controller (whether programmatically or via MainMenu.xib doesn't matter), and tell it to `-showWindow:` when you want the window to show (or become key), and `-close` when you want it to go away.

As for responding to clicking on the Dock icon, the `<NSApplicationDelegate>` method you're looking for is `-applicationShouldHandleReopen:hasVisibleWindows:`.

Problem

I've got an app that I've created in Xcode. It's not document based. How do I make it so that when the user clicks on say, the dock icon, the window reopens? I'm creating everything out the nib that Xcode automagically gave me. I've tried to implement `applicationShouldOpenUntitledFile:` and calling `makeKeyAndVisible` on my app delegate's `window` property, but that messes with the app's icon. (I guess that has to do with icons serving as document previews.) Regardless, I've googled a bit, and mostly found references to Carbon APIs, or document based apps. How does the window creation process work between NSApplicationMain and my app's nib file, how can I replicate that process, and where can I do so?

Original source

Related problems