为什么我的 window 每次访问 `self.window` 时都会加载

Why is my window loaded each time I access `self.window`

我已经使用此代码配置了 window。以前用过。

- (void)awakeFromNib
{
    NSLog(@"self = %p", self);
    [(NSPanel *)self.window setWorksWhenModal: NO];
}

无论如何,每次我访问 self.window 时,window 都是从笔尖加载的。这是一个问题,因为它使这个递归。但这在其他地方也是一个问题,因为我每次都会得到不同的 window!

来自 "NSWindowController":

    /* The window getter will load the nib file (if there is one and it has not yet been loaded) and then return the window. 
If it has to load the window, it will first call -windowWillLoad, then -loadWindow,  then -windowDidLoad.  
To affect nib loading or do something before or after it happens, you should always override those other methods.

        The window setter is used internally from -initWithWindow: or when a controller's nib file is loaded (as the "window" outlet gets connected).
You can also call it yourself if you want to create the window for a window controller lazily, but you aren't loading it from a nib.
This can also be used to set the window to nil for cases where your subclass might not want to keep the window it loaded from a nib, but rather only wants the contents of the window.
Setting the window to nil, after the nib has been loaded, does not reset the -isWindowLoaded state. 
A window controller will only load its nib file once.  This method makes sure the window does not release when closed, and it sets the controller's -windowFrameAutosaveName onto the window and updates the window's dirty state to match the controller's document (if any). 
It also calls -setWindowController: on the window.  You can override this if you need to know when the window gets set, but call super.
    */
    @property (nullable, strong) NSWindow *window;

您的 window NIB 中有哪些对象?我怀疑您已经在 NIB 中创建了 window 控制器 class 的实例。

因此,每当您加载该 NIB(可能通过您在代码中创建的 window 控制器 class 的实例)时,都会创建一个新的 window 控制器实例.该新实例接收 -awakeFromNib 并请求它的 window,这导致它加载 NIB 的另一个实例,并重复该过程。

window 控制器不应在 window NIB 中实例化。 NIB 中的文件所有者占位符应配置为具有 window 控制器的 class。 window 控制器应在代码中实例化并初始化,以便将其自身用作 NIB 的所有者。这将使它填充文件所有者为其保留的位置。

此外,您应该避免覆盖 -awakeFromNib。它可以被意外调用。对于这类任务,覆盖 -windowDidLoad 通常更安全。