我正在尝试从名为userSettings
的EnvironmentObject的值分配给名为categoryData
的类实例,在这里尝试将值分配给类ObserverCategory(userID: self.userSettings.id)
时出现错误
错误提示:Cannot use instance member 'userSettings' within property initializer; property initializers run before 'self' is available
这是我的代码:
这是我的环境对象类:
//user settings
final class UserSettings: ObservableObject {
@Published var name : String = String()
@Published var id : String = "12345"
}
接下来是我尝试分配其值的代码:
//user settings
@EnvironmentObject var userSettings: UserSettings
//instance of observer object
@ObservedObject var categoryData = ObserverCategory(userID: userSettings.id)
class ObserverCategory : ObservableObject {
let userID : String
init(userID: String) {
let db = Firestore.firestore().collection("users/\(userID)/categories") //
db.addSnapshotListener { (snap, err) in
if err != nil {
print((err?.localizedDescription)!)
return
}
for doc in snap!.documentChanges {
//code
}
}
}
}
有人可以指导我解决此错误吗?
谢谢
最佳答案
因为@EnvironmentObject
和@ObservedObject
正在同时初始化。因此,您不能将其中一个用作另一个参数。
您可以使ObservedObject
更加懒惰。因此,您可以在EnvironmentObject
可用时将其关联。例如:
struct CategoryView: View {
//instance of observer object
@ObservedObject var categoryData: ObserverCategory
var body: some View { ,,, }
}
然后像这样传递它:
struct ContentView: View {
//user settings
@EnvironmentObject var userSettings: UserSettings
var body: some View {
CategoryView(categoryData: ObserverCategory(userID: userSettings.id))
}
}