SwiftUI NavigationLink never releases memory
Asked Answered
U

0

15

Take the most basic example app with two screens in a NavigationView:

import SwiftUI

struct ContentView: View {
  var body: some View {
    NavigationView {
      List {
        NavigationLink(destination: SubView()) {
          Text("Go to screen 2")
        }
      }
      .navigationBarTitle("Screen 1", displayMode: .inline)
    }
  }
}

struct SubView: View {
  var body: some View {
    Text("Hello, World!")
      .navigationBarTitle("Screen 2", displayMode: .inline)
  }
}

If you go to screen 2 and press the back button to go back to screen 1, SubView is never released. If you go back and forth multiple times, there will be multiple instances of SubView alive. This feels like a huge problem / memory leak, seems weird it behaves like this by default. Is there a workaround?

Unger answered 25/1, 2020 at 16:2 Comment(7)
What do you mean by release for struct?Xenia
I mean when you profile the app and look at the SwiftUI Instrument, there are multiple instances alive if you go back and forth a few times. The instances are never released from memory, like if there is a retain cycle.Unger
NavigationView is full of bugs. @see #58405225Shortcircuit
@KevinRenskers did you find any solutions?Nutter
No, I didn't. :(Unger
Have your tried NavigationStack / NavigationSplitView instead?Callahan
I'm not seeing this issue on iOS 16.4 betaLesotho

© 2022 - 2024 — McMap. All rights reserved.