When using an @ObservedObject member inside a SubView that is used as the destination of a NavigationLink, that class is never deallocated.
Example:
import Combine
import SwiftUI
struct ParentView: View {
var body: some View {
NavigationView {
List {
ForEach(0..<10) { i in
ZStack {
Text("row \(i)")
NavigationLink(destination: SubView()) {
EmptyView()
}
}
}
}
}
}
}
struct SubView: View {
@ObservedObject private var viewModel = ViewModel()
var body: some View {
Text("bar")
}
}
final class ViewModel: ObservableObject {
init() {
print("init - \(String(describing: type(of: self)))")
}
deinit {
print("deinit - \(String(describing: type(of: self)))")
}
}
Going back and forth the navigation stack will produce as many instances of ViewModel in this case.
