views:

78

answers:

2

I'm trying to observe checkbox status and make appropriate changes in the app when checkbox status changes. In a window manager that manages the window with checkbox I have following observer setup:

- (void)awakeFromNib
{
  [myCheckBox addObserver:self 
                  forKeyPath:@"state" 
                     options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) 
                     context:NULL];
}

- (void)dealloc
{
  [myCheckBox removeObserver:self forKeyPath:@"state"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
  NSLog(@"KeyPath: %@", keyPath);
  NSLog(@"ofObject: %@", object);
  NSLog(@"change: %@", change);
}

I also have wired up myCheckBox to file owner (which is window controller) to appropriate checkbox in the window. However when I run my app observeValueForKeyPath:ofObject:change:context: method is never called.

What am I doing wrong?

+1  A: 

In -awakeFromNib check that myCheckbox is not nil. If it's nil then it's not connected properly in IB.

Edit:

The correct keypath is "cell.state".

Nathan Kinsinger
It is not nil. It gives me instance of NSButton. awakeFromNib is being called when all object in the nib are unarchived and their connections are being already established.
Eimantas
Even if cell.state appears to work, I don't believe that NSButtonCell is documented to be KVO compliant for "state" in all cases. NSCell can represent values though many accessors: setObjectValue:, setStringValue:, setIntegerValue:, setState: ... Observing integerValue and modifying objectValue will not result in a KVO notification, but integerValue will have changed.
Jon Hess
yes, well, it appears that the key path was wrong. Thanks!
Eimantas
You might appear to get all of the notifications that you need with this observance but you're working outside of the API contract of NSButtonCell, and may break in the future or under other circumstances that change the state of the button than a simple setState: call.
Jon Hess
+1  A: 

Unless documented to be Key Value Observing compliant, you should not expect the accessors of a given class to implement KVO support.

Buttons do implement key value binding, so instead of observing the state property you might bind one of your boolean attributes to the button's value binding.

Jon Hess