通常我会使用此方法打开一个带窗口控制器的新窗口
@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属性窗口中的结果立即消失(即我认为已取消分配).
这可能是懒惰的工作
原文链接:https://www.f2er.com/swift/318640.htmlclass AppDelegate : NSApplicationDelegate { lazy var windowController = WindowTestController(windowNibName: "Window") @IBAction func buttonClicked(sender : AnyObject) { windowController.showWindow(sender) } }
self.windowController既不会被分配也不会被nil,直到你试图调用它,此时它将被引入.但直到那个时候.