3

When does the keyWindow get created?

I thought the NSWindow would be created before the corresponding view controller's updateView method was called (Which I call in response to awakeFromNib), however if I create an alert sheet using NSApp's keyWindow, it does not appear correctly.

If I place a button on that view, however, and then bring up the alert when the user clicks on it, the keyWindow is defined, and the alert displays correctly (as expected).

My Application Delegate is almost completely empty.

I don't actually want to display the alert at startup, but I do want to know when the key window is set up. :)

Arafangion
  • 11,517
  • 1
  • 40
  • 72

1 Answers1

4

When does the keyWindow get created?

-[NSApp keyWindow] points to an existing window (e.g. a window that has already been loaded from a nib file) that is currently the key window, typically by sending it -makeKeyAndOrderFront:.

When an application starts, Cocoa:

  1. Loads the main nib file;
  2. Unarchives the contents of the nib file and instantiates its objects;
  3. Reestablishes the connections defined in the nib file;
  4. Sends -awakeFromNib to (a subset of) the nib file objects;
  5. Displays windows that have been marked as Visible at launch time;

as described in the Resource Programming Guide.

If the nib file contains a single window, that window becomes key upon being shown provided it can become a key window, and this happens after -awakeFromNib has been sent.

Also, the documentation for -[NSApplication keyWindow] states that:

This method might return nil if the application’s nib file hasn’t finished loading yet or if the receiver is not active.

  • What if the nib file contains many windows, but only one of which is visible by default? How should other controllers refer to the main or key window without needing to know if the nib file has completed loading yet? (I'm attempting to use the windowDidLoad event on the respective window controllers now, but they aren't being fired). – Arafangion Jul 11 '11 at 05:13
  • Those latter questions in the comment were more or less answered by http://stackoverflow.com/questions/2695671/nswindowcontroller-windowdidload-not-called so accepting your answer because it answers the original question quite well. – Arafangion Jul 11 '11 at 05:19
  • @Ara `NSApplication` and `NSWindow` post some notifications that can be used to coordinate this. You could listen to these notifications, or use the corresponding methods in `NSApplicationDelegate` and `NSWindowDelegate`. Maybe this warrants another question with more details on your architecture and intended behaviour. –  Jul 11 '11 at 08:35
  • I should have looked at the NSApplicationDelegate more. I was looking at the NSWindow notifications, however they weren't being fired. Perhaps due to being loaded as part of a nib. – Arafangion Jul 11 '11 at 08:42