我正在学习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
}
}
}
答案 0 :(得分:0)
哦,亲爱的!
我添加了
的全局对象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未使用,它仍然需要全局范围
希望有人可以从中获得帮助,所以我决定不删除这个