macos – 使用Swift和Cocoa创建nswindow的正确方法
发布时间:2020-12-14 05:38:55 所属栏目:百科 来源:网络整理
导读:通常我会使用此方法打开一个带窗口控制器的新窗口 @class WindowTestController;@interface AppDelegate : NSObject NSApplicationDelegate { IBOutlet NSWindow *window; WindowTestController *windowController;} @property (weak) IBOutlet NSWindow *wi
通常我会使用此方法打开一个带窗口控制器的新窗口
@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实例.即我不需要这样做 if (windowController == nil) 这是正确的还是有其他方法在需要时分配资源,还是我什么都不担心? 干 if (windowController == nil) testWindow = WindowTestController(windowNibName: "Window") } 没有AppDelegate属性窗口中的结果立即消失(即我认为已取消分配).
这可能是懒惰的工作
class AppDelegate : NSApplicationDelegate { lazy var windowController = WindowTestController(windowNibName: "Window") @IBAction func buttonClicked(sender : AnyObject) { windowController.showWindow(sender) } } self.windowController既不会被分配也不会被nil,直到你试图调用它,此时它将被引入.但直到那个时候. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |