通常我会使用这种方法打开一个带有窗口控制器的新窗口
@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
在尝试用Swift完成类似的事情时,我得到了以下内容。
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属性会导致窗口立即消失(我认为是被释放了)。