SwiftUI-向后导航时如何取消初始化StateObject?

时间:2020-10-25 19:33:33

标签: swift navigation swiftui

我希望我的@StateObject在返回后尽快被取消初始化,但是似乎该对象已保存在内存中。 “ Deint ViewModel”不会在向后导航中打印,在我再次导航到我来自的视图之后,它会第一次打印。有没有办法在向后导航时从内存中释放@StateObject

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: TestView(), label: { Text("Show Test View") })
        }
    }
}

struct TestView: View {
    
    @StateObject private var viewModel = ViewModel()
    
    var body: some View {
        Text("Test View")
    }
}

final class ViewModel: ObservableObject {
    deinit {
        print("Deint ViewModel")
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您应该改用@ObservedObject private var viewModel: ViewModel,然后从TestView外部注入新的ViewModel实例