"NSWindow has detected an excessive live window count"

274 Views Asked by At

In a SwiftUI-based application, I'm trying to build a large number of images offscreen, and in the process getting the NSWindow has detected an excessive live window count error. (It's probably irrelevant it's using SwiftUI, but that's what I had at hand.)

Here's a tiny app I created to reproduce the problem.

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBAction func runTest(_ sender: NSMenuItem) {
        for _ in 0..<200 {
            createExample()
        }
    }

    func createExample() {
        let doc = Document()
        let window = doc.makeExampleWindow()

        // I've tried all combinations of the next two lines
        window.close()
        doc.close()
    }
}

This is the code to make the window. I've tried a lot of things to keep the window invisible, of which this is the most pragmatic, but that's not the question here.

extension Document {
    func makeExampleWindow() -> NSWindow {
        let window = NSWindow(contentRect: NSRect(x: 2000,
                                                  y: 2000,
                                                  width: 512,
                                                  height: 512),
                              styleMask: [.borderless],
                              backing: .buffered,
                              defer: false)
        window.center()
        window.contentView = NSHostingView(rootView: ContentView())
        let controller = NSWindowController(window: window)
        addWindowController(controller)

        if let contentVC = controller.contentViewController {
            contentVC.representedObject = self
        }

        window.viewsNeedDisplay = true
        window.isReleasedWhenClosed = true

        return window
    }
}

When you push GO!, you get the error message NSWindow has detected an excessive live window count, and nothing I've tried seems to make the window close properly. After a while, it crashes. I have tried all four combinations of the so-annotated lines, to no avail.

My question is, in the above context, what's the right way to close the window?

0

There are 0 best solutions below