swift中KVO简单使用,监听属性值改变

直接上代码

import UIKit

class ViewController: UIViewController {
    let per = Person()
    override func viewDidLoad() {
        super.viewDidLoad()
        /// 添加观察者
        per.addObserver(self, forKeyPath: "name", options: [.new,.old], context: nil)
    }
    // 点击屏幕通过kvc给Person里面的name赋值
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        let num = Int(arc4random()%10000) + 1
        per.setValue("\(num)", forKey: "name")
    }
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print(keyPath ?? "")
        print("完成回调 -- \(String(describing: per.value(forKey: keyPath!)))")
    }
}
import UIKit
class Person: NSObject {
    var name:String?
}

你可能感兴趣的:(swift中KVO简单使用,监听属性值改变)