KVO-未调用watch()changeHandler

时间:2018-11-06 15:38:44

标签: swift key-value-observing

我要实现的是ViewController观察Model的属性。
但是,没有调用observe()方法changeHandler。
我该如何解决?

ViewController.swift

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        Model.sharedInstance.observe(\.dataSource, options: .new) { (dataSource, change) in
            print("updated! ", dataSource, change) // not called...
        }

        Timer.scheduledTimer(timeInterval: 2.0, target: Model.sharedInstance, selector: #selector(Model.update), userInfo: nil, repeats: true)
    }
}

Model.swift

class Model: NSObject {
    @objc dynamic var dataSource = [Dictionary<String, Any>]()

    class var sharedInstance: Model {
        struct Singleton {
            static let instance: Model = Model()
        }
        return Singleton.instance
    }

    @objc func update() {
        dataSource.append(["key": "value"])
    }
}

1 个答案:

答案 0 :(得分:2)

您需要对观察结果保持强烈的参考感

class ViewController: UIViewController {


    var ob:NSKeyValueObservation! /// the key item

    override func viewDidLoad() {
        super.viewDidLoad()

        ob = Model.sharedInstance.observe(\.dataSource, options: .new) { (dataSource, change) in
            print("updated! ", dataSource, change) // not called...
        }

        Timer.scheduledTimer(timeInterval: 2.0, target: Model.sharedInstance, selector: #selector(Model.update), userInfo: nil, repeats: true)
    }
}


class Model: NSObject {
    @objc dynamic var dataSource = [Dictionary<String, Any>]()

    class var sharedInstance: Model {
        struct Singleton {
            static let instance: Model = Model()
        }
        return Singleton.instance
    }

    @objc func update() {
        dataSource.append(["key": "value"])
    }
}

模型也很简单

class Model: NSObject {

    @objc dynamic var dataSource = [[String:Any]]()

    static let sharedInstance = Model()

    @objc func update() {
        dataSource.append(["key": "value"])
    }
}