Swift KVC/KVO
2022-05-08 本文已影响0人
aven_kang
Swift支持KVC/KVO的条件
属性所在的类、监听器最终继承自NSObject
@objc dynamic修饰对应的属性
class Observer : NSObject {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("observerValue",change?[.newKey] as Any)
}
}
class Person : NSObject {
@objc dynamic var age: Int = 0
var observer : Observer = Observer()
override init() {
super.init()
self.addObserver(observer, forKeyPath: "age", options: .new, context: nil)
}
deinit {
self.removeObserver(observer, forKeyPath: "age")
}
}
var p : Person = Person()
p.age = 20
p.setValue(25, forKey: "age")
打印结果
observerValue Optional(20)
observerValue Optional(25)
block方式的KVO
class Person : NSObject {
@objc dynamic var age:Int = 0
var observation: NSKeyValueObservation?
override init() {
super.init()
observation = observe(\Person.age, options: .new, changeHandler: { Person, Change in
print(Change.newValue as Any)
})
}
}
这个与第一个的写法不同的是,不用单独在创建一个observe类,而且是以block的方式实现的