从NSMenu打开NSWindowController [英] Open NSWindowController from NSMenu

查看:108
本文介绍了从NSMenu打开NSWindowController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代理应用程序(没有停靠栏中的图标)中使用NSMenu。点击此菜单中的按钮时,我想显示一个通用的NSWindowController。

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.

我的菜单按钮动作:

- (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).

任何解决方案?

推荐答案

窗口的原因一秒钟出现,然后消失与ARC有关,以及如何创建窗口控制器实例:

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

在ARC下, myWindow 实例对于定义它的作用域是有效的。换句话说,在到达并运行最后一个 [[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.

通常来说,对于要粘贴的创建的项目或对象,应将它们定义为实例变量,并带有 strong 属性。

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.

例如,您的.h看起来像这样:

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

@class MyWindowController;

@interface MDAppController : NSObject

@property (nonatomic, strong) MyWindowController *windowController;

@end

和修改后的 menuButtonTapped: 方法如下所示:

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

这篇关于从NSMenu打开NSWindowController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆