Béatrice Cassistat Béatrice Cassistat - 3 months ago 26
Swift Question

Opening a new window on a different storyboard

I am developing an OS X app with storyboards. I get the Preview.storyboard with an Entry Point on an anonymous window with a custom ViewController. In the AppDelegate class, I get the following function.

func newPreviewWindow(sender: AnyObject) {
let storyboard = NSStoryboard.init(name: "Preview", bundle: nil)
let initialController = storyboard.instantiateInitialController()
initialController!.showWindow(nil)
initialController!.makeKeyAndOrderFront(nil)
}


When running the code, the window shows, but I get the following exception:

2016-08-11 10:27:12.434 MyApp[1090:290439] -[NSWindowController makeKeyAndOrderFront:]: unrecognized selector sent to instance 0x60000008c350
2016-08-11 10:27:12.434 MyApp[1090:290439] -[NSWindowController makeKeyAndOrderFront:]: unrecognized selector sent to instance 0x60000008c350
2016-08-11 10:27:12.440 MyApp[1090:290439] (
0 CoreFoundation 0x00007fff926284f2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff97c0ef7e objc_exception_throw + 48
2 CoreFoundation 0x00007fff926921ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00007fff92598571 ___forwarding___ + 1009
4 CoreFoundation 0x00007fff925980f8 _CF_forwarding_prep_0 + 120
5 MyApp 0x0000000100005617
...


Based on the exception message and search on Google and StackOverflow, I tried sending a Selector to the
makeKeyAndOrderFront
function this way :

func newPreviewWindow(sender: AnyObject) {
let storyboard = NSStoryboard.init(name: "Preview", bundle: nil)
let initialController = storyboard.instantiateInitialController()
let selector = #selector(AppDelegate.newPreviewWindow(_:))
initialController!.showWindow(nil)
initialController!.makeKeyAndOrderFront(selector) // [A]
}


But then I get the following compile error on line [A]:
Cannot call value of non-function type '((AnyObject?) -> Void)!'


How is the proper way to open the new window or to pass the Selector?

Thanks! :)

Answer

initialController!.makeKeyAndOrderFront(nil) is causing a problem because makeKeyAndOrderFront: is not an NSWindowController method - it belongs to NSWindow (hence the unrecognized selector error). Cast your initial controller to your NSWindowController subclass, then bring the window to the front via the controller's window property:

let windowController = storyboard.instantiateInitialController() as! NSWindowController
windowController.window?.makeKeyAndOrderFront(nil)
Comments