How to pass observed properties to other classes?

喜夏-厌秋 提交于 2020-07-22 03:31:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!