正确的方法来创建nswindow,使用Swift和Cocoa [英] Correct way to create nswindow, using Swift and Cocoa
问题描述
通常我会使用这个方法打开一个带有窗口控制器的新窗口。
Normally I would use this method to open a new window with a window controller
@class WindowTestController;
@interface AppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSWindow *window;
WindowTestController *windowController;
}
@property (weak) IBOutlet NSWindow *window;
@property (strong) WindowTestController *windowController;
- (IBAction) buttonClicked:(id)sender;
@end
然后
#import "AppDelegate.h"
#import "WindowTestController"
@implementation AppDelegate
@synthesize window;
@synthesize windowController;
- (IBAction) buttonClicked:(id)sender {
if (windowController == nil)
testWindow = [[WindowTestController alloc] init];
[windowController showWindow:nil];
}
@end
我有以下的
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var testWindow: NSWindowController = WindowTestController(windowNibName: "Window")
@IBOutlet var window: NSWindow
@IBAction func buttonClicked(sender : AnyObject) {
testWindow.showWindow(nil)
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
}
在这种情况下,我必须为testWindow属性设置一个默认值我创建一个WindowTestController之前我需要它。即我不需要做
In this situation as I have to set a default value for the testWindow property I'm creating an instance of WindowTestController before I need it. i.e. I don't need to do the
if (windowController == nil)
这是正确的,还是有其他方法在需要时分配资源,或者我不担心什么?
Is this correct or is there another method that allocates the resource when required, or am I worrying about nothing?
执行
if (windowController == nil)
testWindow = WindowTestController(windowNibName: "Window")
}
没有AppDelegate属性
Without the AppDelegate property Results in the window immediately disappearing (i.e deallocated I think).
推荐答案
这可能是一个工作 lazy
class AppDelegate : NSApplicationDelegate {
lazy var windowController = WindowTestController(windowNibName: "Window")
@IBAction func buttonClicked(sender : AnyObject) {
windowController.showWindow(sender)
}
}
self.windowController
将不会被分配或nil,直到你尝试调用它,哪一次它将被激活。但到那时为止。
self.windowController
will be neither allocated nor nil until you attempt to call it, at which time it will be inited. But not until that time.
这篇关于正确的方法来创建nswindow,使用Swift和Cocoa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!