KVO(Key-Value Observing)监听属性值,可以用来动态更新页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import UIKit
//属性前加上@objc dynamic实现动态派发 class Preson: NSObject { @objc dynamic var age = 0 }
class ViewController: UIViewController {
let p = Preson() override func viewDidLoad() { super.viewDidLoad() //为p对象的age属性设置监听。 //options为枚举数组,传入了new和old两个值,表示我们需要监听改变前和改变后的值。 //context是Any类型,可以传入任意类型数据,方便在监听到变化时获取该数据。 p.addObserver(self, forKeyPath: "age", options: [.new, .old], context: nil) } //监听 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "age" { print("age被改变了") print(change as Any) } } //释放监听 deinit { p.removeObserver(self, forKeyPath: "age") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { p.age = 20 }
}
|