使用Swift和Cocoa创建NSWindow的正确方法

6

通常我会使用这种方法打开一个带有窗口控制器的新窗口

@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

在尝试用Swift完成类似的事情时,我得到了以下内容。
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实例。也就是说,我不需要做以下操作:
if (windowController == nil) 

这种方法是否正确,还是有其他在需要时分配资源的方法,或者我是在担心一些无关紧要的事情?

正在进行中。

if (windowController == nil) 
       testWindow = WindowTestController(windowNibName: "Window")
}

没有AppDelegate属性会导致窗口立即消失(我认为是被释放了)。

1个回答

9
这可能是一个适合使用“懒加载”技术的工作。
class AppDelegate : NSApplicationDelegate {
    lazy var windowController = WindowTestController(windowNibName: "Window")

    @IBAction func buttonClicked(sender : AnyObject) {
        windowController.showWindow(sender)
    }
}

self.windowController 在你尝试调用它之前既不会被分配也不会为nil,在此时,它将被初始化。但在此之前不会。


@iluvcapra,你是怎么知道这个的?我在哪里可以找到向我展示这个的教程? - Just a coder
我不知道,我只是想出来的 :)自从我发布了这个消息后,苹果已经将“@”符号从lazy关键字中删除了。 - iluvcapra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接