Swift中被观察的类需集成自NSObject
原因:kvo基于runtime机制实现,使用了isa交换(isa-swizzling)
1、创建被观察的对象:
class Person: NSObject {
@objc dynamic var name : String = ""
}
2、添加观察者并响应对象中值的改变
class ViewController: UIViewController {
lazy var p : Person = {
let per = Person()
return per
}()
var observer: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
p.name = "jack"
observer = p.observe(\Person.name, options: [.old, .new]) { (person, change) in
if let old = change.oldValue {
print("old=",old)
}
if let new = change.newValue {
print("new=",new)
}
}
p.name = "hello"
}
}
打印结果:
old= jack
new= hello
3、移除观察者
deinit {
p.removeObserver(p, forKeyPath: "name")
}