我在 SwiftUI 中被认为是新手,并且我有以下 ViewModel。但我不确定 MyViewModel 应该是单例的。这种用法对吗?什么是符合 ObservableObject 的最佳实践/用法?
class MyViewModel: ObservableObject {
static let shared: MyViewModel = MyViewModel()
@Published var result: String = ""
private init() { }
// some functions
}
struct ContentView: View {
@ObservedObject private var vm = MyViewModel.shared
var body: some View {
Text(vm.result)
}
}