Normally I would use this method to open a new window with 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
In trying to do a similar thing in swift I've got 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 as I have to set a default value for the testWindow property I'm creating an instance of WindowTestController before I need it. i.e. I don't need to do the
if (windowController == nil)
Is this correct or is there another method that allocates the resource when required, or am I worrying about nothing?
Doing
if (windowController == nil)
testWindow = WindowTestController(windowNibName: "Window")
}
Without the AppDelegate property Results in the window immediately disappearing (i.e deallocated I think).
This might a be a job for lazy
class AppDelegate : NSApplicationDelegate {
lazy var windowController = WindowTestController(windowNibName: "Window")
@IBAction func buttonClicked(sender : AnyObject) {
windowController.showWindow(sender)
}
}
self.windowController
will be neither allocated nor nil until you attempt to call it, at which time it will be inited. But not until that time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With