可可。如何在托盘应用程序中显示窗口

时间:2013-01-17 22:27:18

标签: objective-c macos cocoa statusbar

我为Mac OS X创建了一个仅限状态栏的应用程序。类似于http://d.pr/i/Covi。我是通过本教程http://cocoatutorial.grapewave.com/2010/01/creating-a-status-bar-application/创建的。现在我有一个问题:如何通过单击“关于”菜单项来显示窗口?我试着这样做:

#import "IGAppDelegate.h"
#import "IGAboutWindowController.h"

@implementation IGAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
}

- (void)awakeFromNib {
    _statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
    [_statusItem setMenu:_menu];
    [_statusItem setTitle:@"LeoHelper"];
    [_statusItem setHighlightMode:YES];
}

#pragma mark - Actions



- (IBAction)quit:(id)sender {
    [NSApp terminate:self];
}

- (IBAction)about:(id)sender {
    IGAboutWindowController *aboutController = [[IGAboutWindowController alloc] init];
    [aboutController showWindow:self];
}
@end

1 个答案:

答案 0 :(得分:2)

我打算猜测你正在使用自动参考计数(ARC)。如果你是,那么这就是about:方法中会发生的事情:

首先创建IGAboutWindowController的本地实例,然后告诉它显示其窗口。这将在屏幕上显示窗口,但是,如果您的项目使用ARC,则窗口将立即消失。原因是只要about:方法结束,IGAboutWindowController的本地实例将自动解除分配,因此,其窗口将从屏幕中删除。

要在ARC托管的项目中成功实施此about:方法,您应该将aboutController定义为IGAppDelegate类的实例变量,如下所示:

@class IGAboutWindowController;

@interface IGAppDelegate : NSObject <...>

@property (nonatomic, strong) IGAboutWindowController *aboutController;

@end

然后像这样实施about:方法:

- (IBAction)about:(id)sender {
    if (self.aboutController == nil)
       self.aboutController = [[IGAboutWindowController alloc] init];
    [aboutController showWindow:self];
}