How to avoid crash when closing NSWindow for agent macOS app

Issue #312

class ClosableWindow: NSWindow {
    override func close() {
        self.orderOut(NSApp)
    }
}

let window = ClosableWindow(
    contentRect: rect,
    styleMask: [.titled, .closable],
    backing: .buffered,
    defer: false
}

window.makeKeyAndOrderFront(NSApp)

The reason is that window is released upon closed if it is not owned by NSWindowController, or we can use releasedWhenClosed

The value of this property is YES if the window is automatically released after being closed; NO if it’s simply removed from the screen.

The default for NSWindow is YES; the default for NSPanel is NO. Release when closed, however, is ignored for windows owned by window controllers. Another strategy for releasing an NSWindow object is to have its delegate autorelease it on receiving a windowShouldClose: message.

Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation