swiftmacoscocoaswift4nswindowcontroller

macOS: Is there a way to access the window controller without crashing?


I have to access the windowController by doing this

let windowController = NSApplication.shared.mainWindow?.windowController as! WindowController

as soon as I try to run this inside viewDidAppear, the app crashes with this

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

The solution, as I found on the web, is to add this line before accessing the windowController:

NSApp.activate(ignoringOtherApps: true) 

This line makes the app active.

But this method does not solve anything for real, because if another app becomes the front app while my app is loading, my app crashes.

Is there any way to make this work?


Solution

  • Your view controller being loaded doesn't mean it's been presented on screen, or even situated within your window. So clearly, you can't do window-related code from viewDidLoad.

    Instead, you should probably register an NSWindowDelegate to your window, but the best course of action depends heavily on exactly what you're trying to do with the window.