为了防止误解这个问题:我很清楚,@Published
属性的publishing个新值是不允许的.This is not my question though.
I want to know if getting / reading a value of 100 property from the background thread (without changing it) is OK.如果不是,原因何在?
例如:
class ViewModel: ObservableObject {
@Published var name: String = ""
func saveName() {
DispatchQueue.global().async {
print("Getting name from background: \(self.name)") // <-- HERE
}
}
}
struct ContentView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
VStack {
TextField("Name", text: $viewModel.name)
Button("Submit") {
viewModel.saveName()
}
}
}
}
直觉上感觉不对劲,但是
- 没有编译错误
- 运行此类代码时未出现运行时错误
- 没有看到任何副作用,而且
- 文件中没有具体说明这是错误的
这是一个有效的代码吗?