Search code examples
iosmacoscocoaswiftkey-value-observing

How to know the sender in KVO?


When I use KVO, I can use the change parameter of function observeValueForKeyPath(...) to know the value. But when there are more than one button added the observer, how can I know which button is changed?

For example as follow:

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

Solution

  • The ofObject: parameter is the object whose property has been changed. In Swift, you can use an optional cast (as?) to verify that the object is of the appropriate type, and then compare it against your buttons:

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