title: How to kill NSWindow properly?
body: <p>Recently, I discovered surprising behavior of <code>NSWindow</code>. It doesn't die while it is displayed on screen regardless of existence of reference to it.</p>
  
  <pre><code>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></pre>
  
  <p>Code above prints <code>start</code> and <code>finish</code> but no <code>W1.deinit</code>. </p>
  
  <p>I tested this on these platforms.</p>
  
  <ul>
  <li>Xcode 10 on Mojave</li>
  <li>Xcode 11 GM (first) on Catalina Beta</li>
  </ul>
  
  <p>And confirmed same result on both platforms.</p>
  
  <hr>
  
  <p>Here are my questions.</p>
  
  <ul>
  <li>Why <code>NSWindow</code> don't die?</li>
  <li>How am I supposed to manage <code>NSWindow</code>?</li>
  <li>How to kill it properly?</li>
  </ul>
  
  <p>As last reference to <code>NSWindow</code> has been removed, it is supposed to die immediately. But it doesn't.</p>
  
  <p>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?</p>
  
  <hr>
  
  <p>Window dies if I <code>close()</code> 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.</p>