我想在 currentStatus 更改时更新 contentview 文本,但是当运行 MLModel 加载模型时,它打印“正在加载资源...”,但 currentStatus 没有更新 ContentView 中的文本,我尝试添加 DispatchQueue.main.async,但是还是不行
ContentView.swift
struct ContentView: View {
@StateObject var model = Content.ViewModel()
var body: some View {
VStack {
Text(model.currentStatus)
.multilineTextAlignment(.center)
.padding(.horizontal)
}
.padding()
.onAppear {
model.inited()
}
}
}
ContentModel.swift
class ContentModel: ObservableObject {
@Published var currentStatus: String = "init..."
func inited() {
currentStatus = "loading resources..."
print("currentStatus: \(self.currentStatus)")
guard let path = Bundle.main.path(forResource: "Unet", ofType: "mlmodelc", inDirectory: "split") else {
fatalError("Fatal error: failed to find the CoreML model.")
}
let resourceURL = URL(fileURLWithPath: path)
let config = MLModelConfiguration()
config.computeUnits = .cpuAndGPU
var loadedModel: MLModel?
do {
loadedModel = try MLModel(contentsOf: resourceURL, configuration: config)
} catch {
print(error)
}
currentStatus = "complete"
print("currentStatus: \(self.currentStatus)")
}
}
应该是@StateObject,而不是@ObservedObject。并考虑将 ContentModel 定义放入 Model 的扩展中,而不是
@ObservedObject var model = ContentModel()
你将拥有:
@StateObject var model = Content.ViewModel()
我相信它使代码更具可读性,但是YMMV。