ios – SwiftUI Parent / Child leaking


Recently I saw an issue in SwiftUI and broke it down to this code for demonstration purposes:

import SwiftUI

// Parent view
struct ContentView: View {
    @State var overlayVisible: Bool = false

    var body: some View {
        VStack {
            Button("Show") {
                withAnimation {
                    overlayVisible = true
                }
            }

            .overlay {
                if overlayVisible {
                    ChildView(onHide: {
                        withAnimation {
                            overlayVisible = false
                        }
                    })
                    .transition(.move(edge: .bottom))
                }
            }
        }
        .padding()
    }
}

// Child view + @StateObject
class ChildViewStore: ObservableObject {
    @Published var alertVisible: Bool = false
}

struct ChildView: View {
    @Environment(\.presentationMode) var presentationMode
    @StateObject var store: ChildViewStore = ChildViewStore()
    
    var onHide: (() -> Void)?
    
    var body: some View {
        Color.gray
            .ignoresSafeArea(.all) // Ignore just for the color
            .overlay{
                VStack {
                    Button("Dismiss") {
                        presentationMode.wrappedValue.dismiss()
                        onHide?()
                    }
                }
            }
    }
}

First I press the button “Show” and after that “Dismiss” and repeat the process a few times.
When I see “Show” again I press the memory inspector in XCode.
I see that “store” of the child view leaked in memory.

Is this expected behavior or a SwiftUI bug?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img