Your Location is: Home > Key-value-observing

observeValueForKeyPath: called for every property, not just the observed property

From: Philippines View: 1968 Trygve 


I have an NSArrayController (itemsController) which hold an array of MyObject. This controller is tied to an NSTableView which has several columns, all bound to different properties.

I want to observe one of these properties elsewhere in the app.

[[self itemsController] addObserver:self forKeyPath:@"selectedObjects.someProperty" options:NSKeyValueObservingOptionNew context:nil];

In the callback:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

I am getting called whenever any property in the selection changes, but I only want to be called when someProperty in a selected object changes.

How can I prevent all these other calls when nothing has really changed?

Observing @"selection.someProperty" has the same results.

Best answer

You also get notified when selectedObjects or selection changes. If you want to get notified when someProperty changes then you have to observe someProperty of the selected objects and remove and add observers when the selection changes.

The superclasses of your observing class could also be observing. Use the context parameter to recognize your notifications. See Best practices for context parameter in addObserver (KVO)