是否有ObservableObject错误 [英] ObservableObject bug or not

查看:84
本文介绍了是否有ObservableObject错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当计数达到3时,我仍然有问题,重置功能仅将其停止,但计数未设置为0.我将重置功能与按钮配合使用,效果很好.我想了解它,希望有人知道它的原因?

I still have the problem when the count reaches 3, the reset function only stops it, but the count is not set to 0. I use the reset function with a button, it works perfectly. i would like to understand it and hope someone knows the reason for it?

import SwiftUI
import Combine
import Foundation

class WaitingTimerClass: ObservableObject {

    @Published var waitingTimerCount: Int = 0

    var waitingTimer = Timer()

    func start() {
        self.waitingTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            self.waitingTimerCount += 1 }}

    func stop() { waitingTimer.invalidate() }

    func reset() { waitingTimerCount = 0; waitingTimer.invalidate() }

}

struct ContentView: View {

    @ObservedObject var observed = WaitingTimerClass()

    var body: some View {
        VStack {
        Text("\(self.observed.waitingTimerCount)")
            .onAppear { self.observed.start() }
                    .onReceive(observed.$waitingTimerCount) { count in
                        guard count == 3 else {return}
                        self.observed.reset()    // does not work
                    }

            Button(action: {self.observed.start()}) {
                Text("Start") }

            Button(action: {self.observed.reset()}) {     // works
                Text("Reset") }

            Button(action: {self.observed.stop()}) {
            Text("Stop") }
           }
        }
    }

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

推荐答案

这是因为reset会在body构造期间更改影响UI的属性,因此将其忽略.应该进行如下更改

It is because reset changes property affecting UI during body construction, so ignored. It should be changed as below

func reset() {
    waitingTimer.invalidate()
    DispatchQueue.main.async {
        self.waitingTimerCount = 0
    }
}

这篇关于是否有ObservableObject错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆