Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Value Observing and NSButton state

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?

like image 317
Eimantas Avatar asked Dec 23 '22 01:12

Eimantas


1 Answers

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

Edit: NSButton.state has the same value as NSButton.cell!.state, but it isn't Key-Value Observable. To be able to observe the value, you'll need to use the \.cell!.state key path.

like image 151
Nathan Kinsinger Avatar answered Mar 06 '23 20:03

Nathan Kinsinger