Search code examples
swiftmacoscocoanswindownswindowcontroller

Cocoa Window Not Showing on macOS Sierra


I have the following code to show a new window in my macOS app. This is within a completionHandler of a NSOpenPanel.

let mainStoryBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let windowController = mainStoryBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "WindowController")) as! NSWindowController
let myController = windowController.window!.contentViewController as! ViewController
myController.imageView.image = mainImage
windowController.showWindow(self)

mainImage is defined above that.

Problem is this code works perfectly on macOS High Sierra, but on macOS Sierra the window sometimes displays for a split second then disappears.

Why would this work on macOS High Sierra but not macOS Sierra?


Solution

  • I was able to solve this by fixing the scope of windowController. Moving that declaration of the variable above the completion handler and setting it to nil to start fixed the issue.

    I also added the NSWindowDelegate and used the function windowWillClose to set windowController back to nil to ensure it is released properly.