如何知道KVO中的发件人?

时间:2014-11-06 12:31:23

标签: ios macos cocoa swift key-value-observing

当我使用KVO时,我可以使用函数observeValueForKeyPath(...)的change参数来知道该值。但是当观察者添加了多个按钮时,我怎么知道哪个按钮被更改了?

例如如下:

check1.addObserver(self, forKeyPath: "cell.state", 
    options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old,
    context: nil)
check2.addObserver(self, forKeyPath: "cell.state", 
    options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old,
    context: nil)

override func observeValueForKeyPath(keyPath: String, ofObject: AnyObject,
    change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void> {

    if keyPath == "cell.state" {
        // I can get the value as follow, but how to know thevalue which button of?
        if change[NSKeyValueChangeNewKey]?.boolValue == true {
            self.isChecked = true
        } else {
            self.IsChecked = false
        }
   }

1 个答案:

答案 0 :(得分:1)

ofObject:参数是其属性已更改的对象。 在Swift中,您可以使用可选的强制转换(as?)来验证对象是否正确 相应的类型,然后将其与您的按钮进行比较:

if let button = ofObject as? NSButton {
    if button == check1 {
        // Checkbox 1 ...
    }
}