问题
I created an instance of UserData so that other classes can observe this instance and show the necessary information by using the username. What I am trying to do here is, when a user is logged in, different classes with user related stored properties will be updated ( i.e. by calling the api) from time to time according to the user activity in the app. However, it shows the error 'Cannot use instance member 'userData' within property initializer; property initializers run before 'self' is available'. Any ideas how to solve this? I am not sure how to pass the data from a single ObservedObject to another.
struct passingData: View {
@ObservedObject var userData = UserData()
@ObservedObject var images = ImageURL(userData: userData)
@ObservedObject var payment = Payment(userData: userData)
var body: some View {
VStack{
TextField("Enter userName", text: $userData.userName)
Text("url is \(images.imageURL)")
Text("Payment detail: \(payment.paymentDate)")
}
}
}
class Payment: ObservableObject{
@Published var paymentDate = ""
@ObservedObject var userData: UserData
init(userData: UserData){
self.userData = userData
loadPaymentDate()
}
func loadPaymentDate(){
self.paymentDate = "last payment date from \(userData.userName) is someDate "
}
}
class ImageURL: ObservableObject{
@Published var imageURL = ""
@ObservedObject var userData: UserData
init(userData: UserData){
self.userData = userData
loadImageURL()
}
func loadImageURL(){
self.imageURL = "123_\(userData.userName).com"
}
}
class UserData: ObservableObject{
@Published var userName = ""
}
回答1:
Here is possible solution:
struct passingData: View {
@ObservedObject var userData: UserData
@ObservedObject var images: ImageURL
@ObservedObject var payment: Payment
init() {
let data = UserData()
self.userData = data
self.images = ImageURL(userData: data)
self.payment = Payment(userData: data)
}
// ... other code
来源:https://stackoverflow.com/questions/62830709/how-to-pass-observed-properties-to-other-classes