Open NSWindowController from NSMenu

2019-05-08 04:17发布

问题:

I'm with a NSMenu in an agent application (without the icon in the dock). When a button from this menu is tapped, I want to show a generic NSWindowController.

My menu button action:

- (IBAction)menuButtonTapped:(id)sender {    
    MyWindowController *myWindow = [[MyWindowController alloc] initWithWindowNibName:@"MyWindowController"];

    [myWindow showWindow:nil];
    [[myWindow window] makeMainWindow];
}

But the window just "flashes" in the screen (it shows and disappears really fast).

Any solution?

回答1:

The reason the window is showing up for a split second and then disappearing has to do with ARC and how you go about creating the instance of the window controller:

- (IBAction)menuButtonTapped:(id)sender {    
    MyWindowController *myWindow = [[MyWindowController alloc]
                    initWithWindowNibName:@"MyWindowController"];
    [myWindow showWindow:nil];
    [[myWindow window] makeMainWindow];
}

Under ARC, the myWindow instance will be valid for the scope where it is defined. In other words, after the last [[myWindow window] makeMainWindow]; line is reached and run, the window controller will be released and deallocated, and as a result, its window will be removed from the screen.

Generally speaking, for items or objects you create that you want to "stick around", you should define them as an instance variable with a strong property.

For example, your .h would look something like this:

@class MyWindowController;

@interface MDAppController : NSObject

@property (nonatomic, strong) MyWindowController *windowController;

@end

And the revised menuButtonTapped: method would look something like this:

- (IBAction)menuButtonTapped:(id)sender {
    if (self.windowController == nil) {
         self.windowController = [[MyWindowController alloc]
            initWithWindowNibName:@"MyWindowController"];
    }
    [self.windowController showWindow:nil];
}


回答2:

Use this:

[[myWindow window] makeKeyAndOrderFront:self];