Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSApplication keyWindow is nil during applicationDidFinishLaunching

Starting with a blank OS X application project, I add the following code to applicationDidFinishLaunching.

func applicationDidFinishLaunching(aNotification: NSNotification) {
    let app = NSApplication.sharedApplication()
    guard let window = app.keyWindow else {
        fatalError("No keyWindow\n")
    }
    print(window)
}

At launch I hit the error case because my local window variable is nil. Yet when I show the contents of the app variable, I see a valid value for _keyWindow. Also notice that the blank GUI Window is being displayed on the screen next to the stack dump.

enter image description here

Why does the keyWindow: NSWindow? property return nil in this case? Thanks

like image 944
Price Ringo Avatar asked Sep 06 '15 00:09

Price Ringo


1 Answers

NSApplication's keyWindow property will be nil whenever the app is not active, since no window is focused for keyboard events. You can't rely on it being active when it finished launching because the user may have activated some other app between when they launched your and when it finished launching, and Cocoa is designed to not steal focus.

To some extent, you may be seeing that happen more when launching from Xcode because app activation is a bit strange in that case. But, still, you must not write your applicationDidFinishLaunching() method to assume that your app is active.

What you're seeing in terms of the app's _keyWindow instance variable is, of course, an implementation detail. One can't be certain about what it signifies and you definitely should not rely on it. However, I believe it's basically the app's "latent" key window. It's the window that will be made key again when the app is activated (unless it is activated by clicking on another of its windows).

like image 124
Ken Thomases Avatar answered Nov 24 '22 18:11

Ken Thomases