How to get old / new values ​​in watchValueForKeyPath in Swift?

I created an observer with .Old | .New .Old | .New . In the handler method, I try to fetch after the values, but the compiler complains: "NSString" does not convert to "NSDictionaryIndex: NSObject, AnyObject

 override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) { let approvedOld = change[NSKeyValueChangeOldKey] as Bool let approvedNew = change[NSKeyValueChangeNewKey] as Bool 
+5
source share
1 answer

You must enter the dictionary of changes in the position you need. Since the change dictionary is [NSObject: AnyObject] , you might have to type it in [NSString: Bool] , since you expect this value.

 let ApprovalObservingContext = UnsafeMutablePointer<Int>(bitPattern: 1) override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) { if context == ApprovalObservingContext{ if let theChange = change as? [NSString: Bool]{ if let approvedOld = theChange[NSKeyValueChangeOldKey] { } if let approvedNew = theChange[NSKeyValueChangeNewKey]{ } } }else{ super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } 

Edit:

With Swift 2.0, here is a complete implementation for a class that uses KVO,

  class Approval: NSObject { dynamic var approved: Bool = false let ApprovalObservingContext = UnsafeMutablePointer<Int>(bitPattern: 1) override init() { super.init() addObserver(self, forKeyPath: "approved", options: [.Old, .New], context: ApprovalObservingContext) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let theChange = change as? [String: Bool] { if let approvedOld = theChange[NSKeyValueChangeOldKey] { print("Old value \(approvedOld)") } if let approvedNew = theChange[NSKeyValueChangeNewKey]{ print("New value \(approvedNew)") } return } super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } deinit { removeObserver(self, forKeyPath: "approved") } } let a = Approval() a.approved = true 
+8
source

Source: https://habr.com/ru/post/1203076/


All Articles