Swift 添加观察者

addObserver形式

创建观察者并添加观察

class People: NSObject {
    // 在Swift中使用KVO来监听属性的变化要加上 @objc 和 dynamic 来修饰
    @objc dynamic var name:String?
    @objc dynamic var sex:String?
    
    init(name:String, sex:String = "M") {
        self.name = name
        self.sex = sex
        super.init()
        for keyPath in ["name", "sex"] {
            // 添加观察者
            addObserver(self, forKeyPath: keyPath, options: [.new, .old], context: nil)
        }
    }
    
    // 监听到值的变化
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        debugPrint("keyPath = \(keyPath!) old = \(change![NSKeyValueChangeKey.oldKey]!) new = \(change![NSKeyValueChangeKey.newKey]!)")
    }
    
    //  析构函数
    deinit {
        for keyPath in ["name", "sex"] {
            // 移除观察者
            removeObserver(self, forKeyPath: keyPath)
        }
    }
}

调用

        var  pp: People?
        pp  = People(name: "飞", sex: "W")
        pp?.name = "凤"
        pp?.sex = "
上一篇:PHP 第三方登录 (QQ登录)


下一篇:【Vue】基础语法(四)计算属性与监视