From d945640401b3a771b67eebb761dabcdcc05647f8 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 1 Sep 2023 09:12:03 -0700 Subject: [PATCH] macos: break reference cycle to window to allow window to free memory Fixes #366 The comment in the Swift code explains what was happening here: > I don't know if this is the right place, but because of WindowAccessor in our > SwiftUI hierarchy, we have a reference cycle between view and window and windows > are never freed. When the window is closed, the window controller is deinitialized, > so we can use this opportunity detach the view from the window and break the cycle. An alternate solution would be to make our reference back to the window "weak" but we appear to not be able to do that with SwiftUI property wrappers such as `@State` and `@Binding` and so on. --- .../Primary Window/PrimaryWindowController.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/macos/Sources/Features/Primary Window/PrimaryWindowController.swift b/macos/Sources/Features/Primary Window/PrimaryWindowController.swift index a77aebf28..bd85972fc 100644 --- a/macos/Sources/Features/Primary Window/PrimaryWindowController.swift +++ b/macos/Sources/Features/Primary Window/PrimaryWindowController.swift @@ -11,4 +11,14 @@ class PrimaryWindowController: NSWindowController { guard let manager = self.windowManager else { return } manager.triggerNewTab(for: window) } + + deinit { + // I don't know if this is the right place, but because of WindowAccessor in our + // SwiftUI hierarchy, we have a reference cycle between view and window and windows + // are never freed. When the window is closed, the window controller is deinitialized, + // so we can use this opportunity detach the view from the window and break the cycle. + if let window = self.window { + window.contentView = nil + } + } }