为什么我的 SwiftUI 文本视图在使用组合更改 viewModel 时不会更新?

lep*_*olt 5 watchkit swiftui combine

我正在使用 SwiftUI 创建一个新的 watchOS 应用程序并尝试使用 MVVM 架构,但是当我的 viewModel 更改时,我似乎无法在我的视图中更新文本视图。

我正在使用 watchOS 6、SwiftUI 和结合。当我认为应该使用 @ObservedObject 和 @Published 时,我正在使用它们,但更改没有像我期望的那样反映出来。

// Simple ContentView that will push the next view on the navigation stack
struct ContentView: View {
    var body: some View {
        NavigationLink(destination: NewView()) {
            Text("Click Here")
        }
    }
}

struct NewView: View {
    @ObservedObject var viewModel: ViewModel

    init() {
        viewModel = ViewModel()
    }

    var body: some View {
        // This value never updates
        Text(viewModel.str)
    }
}

class ViewModel: NSObject, ObservableObject {
    @Published var str = ""
    var count = 0

    override init() {
        super.init()

        // Just something that will cause a property to update in the viewModel
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            self?.count += 1
            self?.str = "\(String(describing: self?.count))"

            print("Updated count: \(String(describing: self?.count))")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Text(viewModel.str)永远不会更新,即使 viewModel 每 1.0 秒都会增加一个新值。我objectWillChange.send()在属性更新时尝试过,但没有任何效果。

我做错了什么吗?

nay*_*yem 4

目前,有一个解决方案,幸运的是我通过实验找到了解决方案。我还没有弄清楚这背后的真正原因是什么。在那之前,您只是不继承NSObject并且一切都应该正常工作。

class ViewModel: ObservableObject {
    @Published var str = ""
    var count = 0

    init() {

        // Just something that will cause a property to update in the viewModel
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            self?.count += 1
            self?.str = "\(String(describing: self?.count))"

            print("Updated count: \(String(describing: self?.count))")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经测试过这个并且它有效。


类似的问题还解决了发布者对象是NSObject. 所以你可能需要重新考虑是否真的需要NSObject子类。如果您无法摆脱NSObject,我建议您尝试链接问题中的解决方案之一。