从单独的笔尖(非模态)显示NSWindow

时间:2012-08-16 13:59:28

标签: objective-c cocoa nib nswindow nsapplication

怎么做?我只是想加载一个窗口并将其显示在主窗口的前面。

NSWindowController* controller = [[NSWindowController alloc] initWithWindowNibName: @"MyWindow"];
NSWindow* myWindow = [controller window];
[myWindow makeKeyAndOrderFront: nil];

此代码显示窗口一会儿然后隐藏它。恕我直言这是因为我没有继续引用窗口(我使用ARC)。 [NSApp runModalForWindow: myWindow];完美无缺,但我不需要以模态方式显示它。

2 个答案:

答案 0 :(得分:6)

是的,如果您没有对窗口的引用,那么当您退出所在的例行程序时,它会立即被拆除。您需要在ivar中对它进行强有力的引用。 [NSApp runModalForWindow: myWindow]是不同的,因为只要NSApplication对象以模态方式运行,它就会保存对窗口的引用。

答案 1 :(得分:1)

您应该执行与以下内容类似的操作,这会为您创建的strong实例创建NSWindowController引用:

·H:

@class MDWindowController;
@interface MDAppDelegate : NSObject <NSApplicationDelegate> {
    __weak IBOutlet NSWindow        *window;
    MDWindowController              *windowController;
}
@property (weak) IBOutlet NSWindow *window;
@property (strong) MDWindowController *windowController;

- (IBAction)showSecondWindow:(id)sender;
@end

的.m:

#import "MDAppDelegate.h"
#import "MDWindowController.h"

@implementation MDAppDelegate

@synthesize window;
@synthesize windowController;

- (IBAction)showSecondWindow:(id)sender {
    if (windowController == nil) windowController =
                        [[MDWindowController alloc] init];
    [windowController showWindow:nil];
}

@end

请注意,您可以使用makeKeyAndOrderFront:的内置NSWindowController,而不是将NSWindow方法直接发送到NSWindowController的{​​{1}}。方法

虽然上面的代码(以及下面的示例项目)使用showWindow:的自定义子类,但您还使用通用NSWindowController并使用NSWindowController创建实例(只需确保文件的nib文件的所有者设置为initWithWindowNibName:而不是像NSWindowController这样的自定义子类。

示例项目:

http://www.markdouma.com/developer/MDWindowController.zip

相关问题