How to get Main Window (App Delegate) from other class (subclass of NSViewController)?

后端 未结 3 1932
情书的邮戳
情书的邮戳 2020-12-23 22:01

I\'m trying to change my windows content, from other class , that is subclass of NSViewController.I\'m trying code below, but it doesn\'t do anything.

[NSApp         


        
3条回答
  •  眼角桃花
    2020-12-23 22:28

    For the mainWindow method the docs say:

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

    I just created a quick test application and I placed the following code:

    NSLog(@"%@", [[NSApplication sharedApplication] mainWindow]);
    

    into my applicationDidFinishLaunching:aNotification method, and into an action method which I connected to a button in the main window of my application.

    On startup, the mainWindow was nil, but when I click the button (after everything is up and running and displayed), the mainWindow was no longer nil.

    NSApplication provides other methods which you may be useful to you:

    • - windows - an array of all the windows;
    • – keyWindow - gives the window that is receiving keyboard input (or nil);
    • – windowWithWindowNumber: - returns a window corresponding to the window number - if you know the number of the window whose contents you wish to replace you could use this;
    • – makeWindowsPerform:inOrder: - sends a message to each window - you could use this to test each window to see if it's the one you are interested in.

    With regard to calling methods on the delegate, what you say gives a warning works fine for me. For example, this works with no warnings:

    NSLog(@"%@", [[[NSApplication sharedApplication]delegate] description]);
    

    What exactly is the warning you receive? Are you trying to call a method that doesn't exist?

提交回复
热议问题