美文网首页
Swift的kvo

Swift的kvo

作者: 今年27 | 来源:发表于2021-10-14 15:04 被阅读0次

Swift的kvo有两种方式
第一种,直接用oc的kvo,但是需要注意的是
1.class必须继承NSObject
2.属性必须加上@objc dynamic 前缀
3.用后必须在合适的地方调用remove方法

import UIKit

class Person: NSObject {
    @objc dynamic var age = 0
}

class ViewController: UIViewController {
    let p = Person()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        p.addObserver(self, forKeyPath: "age", options: [.new, .old], context: nil)
        // Do any additional setup after loading the view.
        p.age = 30
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "age" {
            print(change as Any)
        }
    }
    
    deinit {
        p.removeObserver(self, forKeyPath: "age", context: nil)
    }

}

第二种 swift的方式

import UIKit

class Person: NSObject {
    @objc dynamic var age = 0
}

class ViewController: UIViewController {
    @objc dynamic let p = Person()
    
    var ob: NSKeyValueObservation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.ob = observe(\.p.age, options: [.new, .old], changeHandler: { (_, change) in
            print(change as Any)
        })
        p.age = 30
    }
}

用这种方式的好处就是不用remove观察者

相关文章

网友评论

      本文标题:Swift的kvo

      本文链接:https://www.haomeiwen.com/subject/wccuoltx.html