2014-09-21 29 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

相關問題