关闭视图后,ObservedObject视图模型仍在内存中 [英] ObservedObject view-model is still in memory after the view is dismissed
问题描述
我在SwiftUI和Combine中的内存管理遇到了麻烦.
I am having some trouble with memory management in SwiftUI and Combine.
例如,如果我有一个NavigationView,然后导航到带有TextField的详细信息视图,然后在TextField中输入一个值,然后单击后退"按钮,则下次我转到该视图时,TextField具有先前输入的值
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.
我注意到在取消了详细视图后,视图模型仍在内存中,这可能就是TextField仍然保留值的原因.
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.
在UIKit中,当关闭ViewController时,将释放视图模型,然后在显示ViewController时再次创建它.这里似乎不是这种情况.
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()
}
}
我还注意到,例如,如果我添加另一个视图,比如说在OtherView之后添加SomeOtherView,那么每次我从OtherView中键入TextField时,就会调用SomeOtherView的视图模型中的deinit.谁能解释一下为什么会这样吗?
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?
推荐答案
此外,我注意到,如果我对ContetView进行了更改并且重新评估了该视图,那么我将在内存中拥有两个ViewModels
Moreover, I noticed that if I to a change in ContetView and the view is reevaluated, then I will have two ViewModels in memory
这是由于ViewModel
中的交叉引用,这里是固定的变体
It is due to cross-reference in ViewModel
, here is fixed variant
struct OtherView: View, Constructable {
@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)
}
.onDisappear {
self.viewModel.invalidate() // << here !!
}
}
}
class ViewModel: ObservableObject {
@Published var enteredText = ""
var isValid = false
var cancellable: AnyCancellable?
init() {
print("[>>] created")
cancellable = textValidatedPublisher.receive(on: RunLoop.main)
.assign(to: \.isValid, on: self)
}
func invalidate() {
cancellable?.cancel()
cancellable = nil
print("[<<] invalidated")
}
deinit {
// cancellable?.cancel() // not here !!!
print("[x] done")
}
var textValidatedPublisher: AnyPublisher<Bool, Never> {
$enteredText.map {
$0.count > 1
}.eraseToAnyPublisher()
}
}
-
更新:
导航时是否可以实例化OtherView?
is there a way to instantiate OtherView when navigating?
这是一个解决方案(已通过Xcode 11.4/iOS 13.4测试),但这只是半完成,因为一旦创建,它将一直有效直到导航链接被重新验证(即,背面保留在内存中,直到下一次导航) )
Here is a solution (tested with Xcode 11.4 / iOS 13.4), but this is only half-a-deal, because once created it will be alive until navigation link revalidated (ie. on back it remains in memory until next navigate)
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination:
// create wrapper view with type of view which creation
// is deferred until navigation
DeferCreatingView(of: OtherView.self)) {
Text("Press Here")
}
}
}
}
protocol Constructable {
init()
}
struct DeferCreatingView<T: View & Constructable>: View {
var ViewType: T.Type
init(of type: T.Type) {
ViewType = type
}
var body: some View {
ViewType.init() // << create only here
}
}
struct OtherView: View, Constructable {
// .. not changed code from first part
}
这篇关于关闭视图后,ObservedObject视图模型仍在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!