[英]macOS: Correct way of exposing Swift properties to Cocoa Bindings
[英]Correct way to create nswindow, using Swift and Cocoa
通常我會使用此方法打開一個帶窗口控制器的新窗口
@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屬性窗口中的結果會立即消失(即我認為已取消分配)。
這可能是lazy
的工作
class AppDelegate : NSApplicationDelegate {
lazy var windowController = WindowTestController(windowNibName: "Window")
@IBAction func buttonClicked(sender : AnyObject) {
windowController.showWindow(sender)
}
}
self.windowController
既不會被分配也不會被nil,直到你試圖調用它,此時它將被引入。 但直到那個時候。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.