Neigaard
Neigaard

Reputation: 4050

Close NSWindow but do not nil it

I have a window-less app with the "Application is agent" set to YES. In that app I have a "let mainWindow: NSWindow" and with the click on a menu item I do the following:

func createNewWindow(){
    mainWindow.center()
    mainWindow.hidesOnDeactivate = true
    mainWindow.isMovableByWindowBackground = true
    mainWindow.backgroundColor = NSColor(calibratedHue: 0, saturation: 0, brightness: 1, alpha: 0.4)
    mainWindow.contentViewController = searchView
    mainWindow.makeKeyAndOrderFront(nil)
    NSApp.activate(ignoringOtherApps: true)
}

If I click outside my window or in any way shift focus to another app, my window closes and I have to click my menu item to open it again. Now this is what I want, so this is great. But if I in the view controller call "self.view.window?.close()" and there after click my menu item to open my window again, I get a bad access when accessing mainWindow, so I am guessing something has set it to nil when I close it.

How do I close my window in the same way as when I click outside the window? Or how do I otherwise prevent the bad access error?

Thank you
Søren

Upvotes: 1

Views: 727

Answers (1)

vadian
vadian

Reputation: 285069

Not something, you set it to nil when you close the window.

From the documentation of close()

If the window is set to be released when closed, a release message is sent to the object after the current event is completed. For an NSWindow object, the default is to be released on closing, while for an NSPanel object, the default is not to be released. You can use the isReleasedWhenClosed property to change the default behavior.

Either change the behavior or call orderOut(_:) which doesn't release the window.

Upvotes: 3

Related Questions