每次从SecondVM
推送到新的View并且ContentView
完成他的工作时,我都无法分配ContentVM
。
说明
推送到Second
视图后,ObservableObject
中的任务完成后,ContentVM
被释放。
我的示例代码如下ContentView
和`ContentVM:
final class ContentVM: ObservableObject {
@Published var title = "Start"
init() {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.title = "Changed"
}
}
}
struct ContentView: View {
@ObservedObject var vm = ContentVM()
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Second()) {
Text("Go To second")
}
Spacer()
.frame(height: 40)
Text(vm.title)
}
}
}
}
和Second
和SecondVM
final class SecondVM: ObservableObject {
@Published var name: String = ""
func getName() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.name = "TEST"
}
}
}
struct Second: View {
@ObservedObject var vm = SecondVM()
var body: some View {
Text(vm.name)
.padding(50)
.background(vm.name.isEmpty ? Color.white : Color.black)
.foregroundColor(Color.white)
.onAppear {
self.vm.getName()
}
}
}
正如您在视频波纹管上看到的那样,仅当我按下Second
视图时,问题才出现。黑色矩形正确显示,完成ContentVM
中的任务之后,该黑色矩形由于取消分配SecondVM
而消失。如何避免这种行为?
答案 0 :(得分:1)
这是解决方案-使链接目标相等,因此,当ContentView根据自己的状态更新时,它不会重新创建目标视图(否则将发生此现象,并且是观察到的问题的根源)。
通过Xcode 11.5b2测试
// in ContentView, id can be any type but constant in this case
NavigationLink(destination: Second(id: 1).equatable()) {
Text("Go To second")
}
// SecondView
struct Second: View, Equatable {
let id: Int
static func == (lhs: Second, rhs: Second) -> Bool {
lhs.id == rhs.id
}
@ObservedObject var vm = SecondVM()
// .. other code