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

2024-04-02

通常我会使用此方法通过窗口控制器打开一个新窗口

@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

在尝试快速做类似的事情时,我得到了以下内容

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) 

这是正确的还是有另一种方法可以在需要时分配资源,或者我什么都不担心?

Doing

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

如果没有 AppDelegate 属性,窗口会立即消失(即我认为已解除分配)。


这可能是一份工作lazy

class AppDelegate : NSApplicationDelegate {
    lazy var windowController = WindowTestController(windowNibName: "Window")

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Swift 和 Cocoa 创建 nswindow 的正确方法 的相关文章

随机推荐