检查更改是否为键值中的类型initial观察swift 3

时间:2017-04-06 03:53:16

标签: swift key-value-observing

当覆盖observeValue以进行键值观察时,您可以通过更改来查看更改是新的还是旧的?[.newKey]或更改?[.oldKey]。但是,如何检查是否没有变化,但更改只是首次添加观察者时的初始值

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
    let newchange = change?[.newKey]
    let oldchange = change?[.oldKey]
}

1 个答案:

答案 0 :(得分:2)

来自documentation

  

通知中的更改字典将始终包含   如果还指定了new但是永远不会包含new​Key条目   old​Key条目。 (在初始通知中的当前值   观察到的属性可能很旧,但它对观察者来说是新的。)

因此,如果您想知道某个特定更改是否为初始值,请在添加观察者时同时请求.new.old,并且在此处没有.oldKey改变字典,这意味着这是初始值。

这里有一些快速的游乐场代码来演示:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

@objc class Test: NSObject {
    var blah: String? = "Test" {
        willSet {
            self.willChangeValue(forKey: "blah")
        }
        didSet {
            self.didChangeValue(forKey: "blah")
        }
    }
}

var test = Test()

@objc class Observer: NSObject {
    func blah() {
        test.addObserver(self, forKeyPath: "blah", options: [.initial, .new, .old], context: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if let change = change {
            print(change)
        }
    }
}

var observer = Observer()

observer.blah()

test.blah = "Test2"
test.blah = nil

这是输出:

[__C.NSKeyValueChangeKey(_rawValue: new): Test, __C.NSKeyValueChangeKey(_rawValue: kind): 1]
[__C.NSKeyValueChangeKey(_rawValue: new): Test2, __C.NSKeyValueChangeKey(_rawValue: kind): 1, __C.NSKeyValueChangeKey(_rawValue: old): Test]
[__C.NSKeyValueChangeKey(_rawValue: new): <null>, __C.NSKeyValueChangeKey(_rawValue: kind): 1, __C.NSKeyValueChangeKey(_rawValue: old): Test2]