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
And then
#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
In trying to do a similar thing in swift I've got the following
在尝试快速做类似的事情时,我得到了以下内容
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
}
}
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
在这种情况下,我必须为testWindow属性设置一个默认值,我在创建WindowTestController的实例之前需要它。即我不需要这样做
if (windowController == nil)
Is this correct or is there another method that allocates the resource when required, or am I worrying about nothing?
这是正确的还是有其他方法在需要时分配资源,还是我什么都不担心?
Doing
if (windowController == nil)
testWindow = WindowTestController(windowNibName: "Window")
}
Without the AppDelegate property Results in the window immediately disappearing (i.e deallocated I think).
没有AppDelegate属性窗口中的结果立即消失(即我认为已取消分配)。
1 个解决方案
#1
9
This might a be a job for lazy
这可能是懒惰的工作
class AppDelegate : NSApplicationDelegate {
lazy var windowController = WindowTestController(windowNibName: "Window")
@IBAction func buttonClicked(sender : AnyObject) {
windowController.showWindow(sender)
}
}
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.
self.windowController既不会被分配也不会被nil,直到你试图调用它,此时它将被引入。但直到那个时候。
#1
9
This might a be a job for lazy
这可能是懒惰的工作
class AppDelegate : NSApplicationDelegate {
lazy var windowController = WindowTestController(windowNibName: "Window")
@IBAction func buttonClicked(sender : AnyObject) {
windowController.showWindow(sender)
}
}
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.
self.windowController既不会被分配也不会被nil,直到你试图调用它,此时它将被引入。但直到那个时候。