The correct way to create nswindow using Swift and Cocoa

Normally I would use this method to open a new window using 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 

When trying to do this in swift, I have 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, since I have to set the default value for the testWindow property, I create an instance of WindowTestController before I need it. that is, I do not need to do

 if (windowController == nil) 

Is this correct or is there another method that allocates the resource when it is required, or am I not worried about anything?

Performance

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

Without the AppDelegate property. The results in the window disappear immediately (e.g. deallocated, I think).

+6
source share
1 answer

This may be a quest for lazy

 class AppDelegate : NSApplicationDelegate { lazy var windowController = WindowTestController(windowNibName: "Window") @IBAction func buttonClicked(sender : AnyObject) { windowController.showWindow(sender) } } 

self.windowController will not be allocated nor a nil until you try to call it, and at that time it will be turned on. But not earlier than this time.

+9
source

Source: https://habr.com/ru/post/970849/


All Articles