海湾全球范围

KVO Global scope

我正在学习 MVVM,所以我在 属性

上添加了观察者
 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" 


}

当文本字段值从视图控制器更改时应该调用观察者所以我从 updateField 方法

设置了 registerModel.confirmPassword = str

但是print语句没有被执行

但如果我从 init 方法更改值,则观察者正在工作!

如何让它全球化?

额外信息

我如何改变属性

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
        }
    }
}

天啊!!

我已经为

添加了全局对象
private var confirmPasswordObserver : NSKeyValueObservation?

并使用这个对象。

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

现在正在工作。但我想知道是否有人可以向我解释这一点。即使 confirmPasswordObserver 未使用,它仍然需要全局范围

希望有人能从中得到帮助所以我决定不删除这个