0

文档说 [when .initialis used]:如果还指定了 new,则通知中的更改字典将始终包含一个 newKey 条目,但永远不会包含 oldKey 条目。

在基于块的 KVO 观察者中接收change结构体,在哪里oldValue使用。

oldValue有野生型Optional<Optional<Any>>

由于“Any is not Comparable”错误,任何形式的直接比较(使用 nil、.some(nil) 等)都会失败。

如何检查观察者的呼叫是否是初始的?

更新

出色地。

我正在观察value: Any一些attribute. 真正value是由内部的二进制数据构造的,attribute并且具有交付它的类型,Bool?在这种情况下是真正的类型。观察者被正确触发,这不是问题。

observe(\ViewController.attribute.value, options: [.initial, .new, .old]) { (_self, change) in
    guard change.newValue as? Bool != change.oldValue as? Bool // does not work in initial
    else { 
        return 
    }
    ...
}

在最初的情况下,我有

(lldb) po change
▿ NSKeyValueObservedChange<Optional<Any>>
  - kind : __C.NSKeyValueChange
  ▿ newValue : Optional<Optional<Any>>
    ▿ some : Optional<Any>
      - some : <null>
  ▿ oldValue : Optional<Optional<Any>>
    - some : nil
  - indexes : nil
  - isPrior : false

新值为nil( attribute.value == .none)。根据文档,旧值不得包含。我应该怎么做才能确保它不是真的被包含在内?

4

1 回答 1

0

似乎我发现了:

guard
    case let oldValue? = change.oldValue, oldValue == nil ||
    (change.newValue as? Bool != oldValue as? Bool)
else
{
    return
}
于 2020-04-10T16:11:04.910 回答