ios swift kvo代码示例

1.示例代码

class PersonKVO: NSObject {    
    @objc dynamic var name = "li"
    @objc dynamic var age = 12

}
class ViewController: UIViewController {
    
    var person: PersonKVO = PersonKVO()
    
    @IBAction func btnClick(_ sender: Any) {
        person.name = "8574"
        person.age = 100
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.person.addObserver(self, forKeyPath: "age", options: .new, context: nil)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(keyPath!)
        if let age = change?[.newKey] {
            print(age)
        }
        let person: PersonKVO = object as! PersonKVO
        print(person.name)
    }

}

打印结果:
age
100
8574

2.监听不回调问题

iOS Swift KVO监听不回调问题

参考博客:

Swift 5中的KVO指南和代码示例

相关博客:

iOS KVO(NSKeyValueObserving,Key-Value Observing)

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页