Get value from KVO - returning NSConreteValue

2019-08-07 01:09发布

问题:

I have the following KVO observer:

 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if context == &kvoContext {
            if (keyPath == "transform") {
                if let transform = change![NSKeyValueChangeNewKey] {
                    print("transform: \(transform)")
                    overlay.transform = transform as! CGAffineTransform
                }
            }
        }
    }

Which prints out:

transform: CGAffineTransform: {{1, 0, 0, 1}, {0, 0}}

However, in my variable window I see transform as an NSConcreteValue:

And I crash on that last line trying to set overlay.transform:

fatal error: unexpectedly found nil while unwrapping an Optional value

How do I retrieve that value?

回答1:

Your transform is being automatically boxed into an NSValue object. You'll need to access it like

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
  if context == &kvoContext {
    if (keyPath == "transform") {
      if let transform = change?[NSKeyValueChangeNewKey] as? NSValue {
        overlay.transform = transform.CGAffineTransformValue()
      }
    }
  }
}