xcode 在应用程序委托中获取主窗口控制器的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26188013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get instance of main window controller in app delegate
提问by redeyes
I know that, for iOS, you can reference the root view controller from the app delegate like so:
我知道,对于 iOS,您可以从应用程序委托中引用根视图控制器,如下所示:
var rootViewController = self.window!.rootViewController
var rootViewController = self.window!.rootViewController
How does one reference the main window controller from the app delegate when targeting OS X? I would like to pass a variable (the managed object context) this way, as I have read that it is a good solution for referencing the moc.
以 OS X 为目标时,如何从应用程序委托中引用主窗口控制器?我想以这种方式传递一个变量(托管对象上下文),因为我已经读到它是引用 moc 的一个很好的解决方案。
回答by seb
You can access the NSWindowController instance of the main NSWindow like this:
你可以像这样访问主 NSWindow 的 NSWindowController 实例:
NSApplication.sharedApplication().mainWindow?.windowController
回答by Phill Apley
The ! in earlier answers will cause a crash if the window is hidden, so I recommend caching the window either like this or using a computed property:
这 !如果窗口被隐藏,在早期的答案中会导致崩溃,所以我建议像这样或使用计算属性缓存窗口:
var mWindow: NSWindow? = nil
func mainWindowCached() -> NSWindow? {
if let window = NSApplication.shared.mainWindow {
self.mWindow = window
}
return self.mWindow
}
回答by Parvesh
You can access like this:
您可以这样访问:
NSApplication.shared().mainWindow?.contentViewController as! YourViewController;