KVO Global scope

Prashant Tukadiya

I am learning MVVM so I added observer on property

 init(model: RegisterUserModel = RegisterUserModel()) {
    self.registerModel = model

    let confirmPasswordObserver = self.registerModel.observe(\RegisterUserModel.confirmPassword) {[unowned self] (model, value) in
        print("Confrim Password Observeer called with value :\(self.registerModel.confirmPassword)")
    }
   // self.registerModel.confirmPassword = "CALLED WITH THIS LINE INSIDE INIT FUNC ONLY" 


}

observer should be called when textfield value change from view controller so I have set registerModel.confirmPassword = str from updateField Method

But print statement is not been executed

but if I change value from init method then observer is working !!

How to make it global ?

EXTRA Info

How I change property

extension RegisterViewModel {

    func updateField (field:RegisterFields, withString str:String) {
        switch field {
        case .firstName:
            registerModel.firstName = str

        case .lastName:
            registerModel.lastName = str

        case .email:
            registerModel.email = str

        case .phone:
            registerModel.phone = str

        case .city:
            registerModel.city = str

        case .password:
            registerModel.password = str
            confirmPassword.value = confirmPassword.value

        case .confirmPassword:
            registerModel.confirmPassword = str //SHOULD BE CALLED FROM HERE
        }
    }
}
Prashant Tukadiya

Oh dear !!

I have added global object for

private var confirmPasswordObserver : NSKeyValueObservation?

and use this object.

  confirmPasswordObserver = self.registerModel.observe(\RegisterUserModel.confirmPassword) {[unowned self] (model, value) in
            print("Confrim Password Observeer called with value :\(self.registerModel.confirmPassword)")
        }

And it is working now. But I wonder if any one can exaplin this to me. even though confirmPasswordObserver is unused still it need global scope

Hope some one can take help from it so I decided not to delete this

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related