Open NSWindowController from NSMenu

微笑、不失礼 提交于 2020-01-13 11:52:37

问题


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];


来源:https://stackoverflow.com/questions/13441718/open-nswindowcontroller-from-nsmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!