SwiftUI: memory leaks if update environment object in a view

Hi! I encountered a memory leak issue when trying to use environment object to route the view display of the application. Can you help me to get some idea why the leak happens and how to resolve it?

I use the following AppRootView as the contentView in SceneDelegate.
Code Block
struct AppRootView: View {
    @EnvironmentObject var appState: AState
    var body: some View {
        appState.updateIsSignedAgreementUpToDate()
        return VStack{
            if false {
                MainPageView()
            }
            else {
                AgreementView()
            }
        }
    }
}


Following is the class I use for environment variable
Code Block
class AState : ObservableObject {
    static let sharedInstance = AState()
@Published var isSignedAgreementUpToDate : Bool = false
    func updateIsSignedAgreementUpToDate() {
        self.isSignedAgreementUpToDate = false
    }
private init() {
}
}


When I run the code, neither the MainPageView nor the AgreementView will display, and the memory usage is keep increasing. I added a breakpoint to the AppRoot view, and found that it is running again and again. However, from the call stack I cannot find any clue why this happens.

If I do the following, the application will start without memory leak:
  1. comment out the calling of appState.updateIsSignedAgreementUpToDate() in AppRootView; or

  2. comment out the line of self.isSignedAgreementUpToDate = false in AState class; or

  3. replace the Stack in AppRootView to simply a MainPageView or a AgreementView.

I am testing the app in Simulator with iOS14, with Xcode 12.

Thank you!

Replies

I’m confused. Why do you make AState a singleton and pass it through the environment?
Hi wingover,

That's because I have a lot of data want to share in the application across different pages. I just made a singleton class and put all the data inside. Does that cause issue?
Thank you!

Sui