使用Timer时SwiftUI中ObservedObject的奇怪行为

时间:2020-06-27 01:13:34

标签: swiftui

在下面的程序中,为每个计时器事件调用Bar的初始化程序。有人知道这个问题的原因吗?

此问题在模拟器和真实设备iOS 13.5中均会发生。我在Xcode 11.5上进行了测试。

enter image description here

import SwiftUI
import Combine

class Foo: ObservableObject {
    @Published var value: Int
    
    init() {
        print("init")
        self.value = 10
        
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (_) in
            self.value += 1
        }
    }
}

class Bar: ObservableObject {
    @Published var value: Int
    
    init() {
        print("Bar")
        self.value = 100
    }
}

struct FirstView: View {
    @EnvironmentObject var foo: Foo
    @ObservedObject var bar = Bar()
    
    var body: some View {
        VStack {
            Text("\(foo.value)")
            Text("\(bar.value)")
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var foo: Foo

    var body: some View {
        VStack {
            Text("\(foo.value)")
            FirstView()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1 个答案:

答案 0 :(得分:0)

Foo作为ObservedObject的任何时间发布更改,都会导致“观察到”它的视图重新呈现其body

FooContentView中被观察到,因此Foo的变化使其重新计算其body

VStack {
    Text("\(foo.value)")
    FirstView()
}

这将调用FirstView(),然后依次调用Bar()