Open NSWindowController from NSMenu

帅比萌擦擦* 提交于 2019-12-05 15:06:57

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

Use this:

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