I am having some trouble with memory management in SwiftUI and Combine.
For example, if I have a NavigationView and then navigate to a detail view with a TextField, and enter a value in the TextField and tap on the back button, next time I go to that view the TextField has the previously entered value.
I noticed that the view-model is still in memory after the detail view is dismissed, and that's probably why the TextField still holds a value.
In UIKit, when dismissing a ViewController, the view-model will be deallocated and then created again when the ViewController is presented. This seems to not be the case here.
I attach some minimum reproductible code for this issue.
import SwiftUI
import Combine
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: OtherView()) {
Text("Press Here")
}
}
}
}
struct OtherView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
TextField("Something", text: $viewModel.enteredText)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
print("Tap")
}) {
Text("Tapping")
}.disabled(!viewModel.isValid)
}
}
}
class ViewModel: ObservableObject {
@Published var enteredText = ""
var isValid = false
var cancellable: AnyCancellable?
init() {
cancellable = textValidatedPublisher.receive(on: RunLoop.main)
.assign(to: .isValid, on: self)
}
deinit {
cancellable?.cancel()
}
var textValidatedPublisher: AnyPublisher<Bool, Never> {
$enteredText.map {
$0.count > 1
}.eraseToAnyPublisher()
}
}
I also noticed that, if for example, I add another view, let's say SomeOtherView after OtherView, then each time I type in the TextField from OtherView, then the deinit from SomeOtherView's view-model is called. Can anyone please also explain why this happens?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…