Cross posted to https://stackoverflow.com/questions/57916099/how-to-kill-nswindow-properly.
Recently, I discovered surprising behavior of
NSWindow
. It doesn't die while it is displayed on screen regardless of existence of reference to it.
import Foundation
import AppKit
final class W1: NSWindow {
deinit {
print("W1.deinit")
}
}
print("start")
autoreleasepool {
var w1:W1? = W1()
w1?.setFrame(NSRect(x: 0, y: 0, width: 100, height: 100), display: true)
w1?.orderFront(nil)
w1 = nil
}
print("finish")
RunLoop.main.run()
Code above prints
start
and finish
but no W1.deinit
.I tested this on these platforms.
- Xcode 10 on Mojave
- Xcode 11 GM (first) on Catalina Beta
And confirmed same result on both platforms.
Here are my questions.
- Why
don't die?NSWindow
- How am I supposed to manage
?NSWindow
- How to kill it properly?
As last reference to
NSWindow
has been removed, it is supposed to die immediately. But it doesn't.If it do not die, it means there's another "hidden" reference to it or AppKit have "special" behavior on windows. What's the reason?
Window dies if I
close()
it before removing last reference to it. But I am not sure whether this is really proper/designed way to kill it as it's out of Cocoa/Swift lifetime management rules.