Swift中KVO的简单示例

利用observ函数实现

class Child: NSObject {
    @objc dynamic var age: Int
    var name:String
    init(age: Int,name: String) {
        self.age = age
        self.name = name
    }

    func growup() {
        self.age += 1
    }
}


let mary = Child(age: 10, name: "Mary")
//默认开启观察
let observation = mary.observe(\.age, options: .new) { child, change in
    print("\(child.name) is \(change.newValue ?? -1)  years old." )
}
mary.growup()
mary.growup()
//停止观察
observation.invalidate()
mary.growup()

运行结果:

Mary is 11  years old.
Mary is 12  years old.

利用OC的方式实现

//被观察者
class Child: NSObject {
    @objc dynamic var age: Int
    var name:String
    init(age: Int,name: String) {
        self.age = age
        self.name = name
    }

    func growup() {
        self.age += 1
    }
}

//观察者
class Observer: NSObject {
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let keyPath = keyPath, keyPath == "age", let change = change, let m = object as? Child else {
            return
        }
        guard let age = change[.newKey] else {return}
        print("\(m.name) is \(age)  years old." )

    }
}

let observer = Observer()
let mary = Child(age: 10, name: "Mary")
//注册
mary.addObserver(observer, forKeyPath: "age",options: .new, context: nil)
mary.growup()
mary.growup()
//移除
mary.removeObserver(observer, forKeyPath: "age")
mary.growup()

运行结果:

Mary is 11  years old.
Mary is 12  years old.

你可能感兴趣的:(Swift中KVO的简单示例)