Swift中使用KVO

2018-09-13  本文已影响0人  AndyYaWei

自己使用swift4.0写了一个例子

class FirstViewController: UIViewController {
    @objc dynamic var age = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.addObserver(self, forKeyPath: "age", options: [NSKeyValueObservingOptions.old, NSKeyValueObservingOptions.new], context: nil)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "age" {
            if let newValue = change?[NSKeyValueChangeKey.newKey] {
                print("age changed: \(newValue)")
            }
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.age += 1
    }

注意事项

  1. 观察者和被观察者都必须是 NSObject 的子类;
  2. 观察的属性需要使用 @dynamic 关键字修饰。
上一篇 下一篇

猜你喜欢

热点阅读