通常我会使用此方法通过窗口控制器打开一个新窗口
@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 属性,窗口会立即消失(即我认为已解除分配)。