"Accessing StateObject's object without being installed on a View. This will create a new instance



我目前正在学习Paul Hudson的SwiftUI 100天训练营,我遇到了一个挑战,要求将对象从结构(View(转移到类(ViewModel(中,以便在项目中创建MVVM体系结构。然而,当初始化结构初始值设定项中的某个变量时,我会收到运行时警告下面是我的视图结构中初始化的对象:

@StateObject private var viewModel = EditViewViewModel()
@Environment(.dismiss) var dismiss
var onSave: (Location) -> Void

结构的初始值设定项:

init(location: Location, onSave: @escaping (Location) -> Void) {
self.onSave = onSave
viewModel.location = location // WARNING: Accessing StateObject's object without being installed on a View. This will create a new instance each time.
}

这是导致问题的变量,也是我的ViewModel:的初始值设定项

var location: Location

init() {
self.location = Location(id: UUID(), name: "", description: "", latitude: 0.0, longitude: 0.0)
self.name = ""
self.description = ""
}

这个问题与这个问题重复。

以下是SwiftUIMVVM的最小示例。将您的位置更新放入onAppear,然后将其从init中删除。

import SwiftUI
struct NumberView: View {
@StateObject private var viewModel = NumberViewModel()
init() {
// Accessing StateObject's object without being installed on a View. This will create a new instance each time.
// viewModel.increaseNum()
}
var body: some View {
VStack {
Text("Num: (viewModel.num)")
Button("Increase num", action: {
// No warnings about accessing StateObject's object without being installed on a View
viewModel.increaseNum()
print("New num to viewModel: (viewModel.num)")
})
}
.onChange(of: viewModel.num) { newNum in
print("New num from viewModel: (newNum)")
}
.onAppear {
// No warnings about accessing StateObject's object without being installed on a View
viewModel.increaseNum()
}
}
}
class NumberViewModel: ObservableObject {
@Published private(set) var num: Int = 0
func increaseNum() {
num += 1
}
}

相关内容

最新更新