2014-09-21 95 views
5

我用.Old | .New选项创建了一个观察者。在该处理方法我尝试值前后取,但编译器抱怨:“的NSString”是无法转换为“NSDictionaryIndex:NSObject的,AnyObject如何在swift中的observeValueForKeyPath中获取旧/新值?

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 

回答

8

你必须强制转换的变化字典你想要什么。由于更改字典是[NSObject:AnyObject],因此您可能必须键入将其转换为[NSString:Bool],因为您预计该类型的值。

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) 
    } 
    } 

编辑:

与SWIFT 2.0,这里是一个使用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 
+0

此代码不能编译。错误:'[String:AnyObject]?'不可转换为'[NSString:Bool]'' – RaffAl 2016-03-01 10:27:24

+1

@Bearwithme立即检出更新。 – Sandeep 2016-03-01 11:25:45

+0

太棒了!非常感谢您的解决! – RaffAl 2016-03-01 11:28:26

相关问题