Key Value Observing and NSButton state

风格不统一 提交于 2019-12-22 10:49:12

问题


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:


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".




回答2:


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.



来源:https://stackoverflow.com/questions/3222429/key-value-observing-and-nsbutton-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!