Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Value Observing in Cocoa, introspecting the change property

I'm using key value observing on a boolean property an NSObject method:

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

The most interesting part of the value for this key path is a BOOL which is constantly flipping between YES/NO. The most I get out of the change dictionary is kind = 1. Is there anyway without probing the object I'm observing to see what the actual change value is?

Thanks.

like image 343
Coocoo4Cocoa Avatar asked May 11 '09 21:05

Coocoo4Cocoa


People also ask

What is key-value observing?

Overview. Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It's useful for communicating changes between logically separated parts of your app—such as between models and views.

What is key-value Coding and key-value observing?

Using a mechanism called key-value coding (KVC), you can manipulate object properties indirectly. With KVC comes the ability to observe changes to a particular key value, which is known as key-value observing (KVO).

What framework is KVO key-value observing a part of?

Key-Value Observing, KVO for short, is an important concept of the Cocoa API. It allows objects to be notified when the state of another object changes.

What is key-value coding?

About Key-Value Coding. Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface.


1 Answers

Firstly, you specify NSKeyValueObservingOptionNew:

[theObject addObserver: self
            forKeyPath: @"theKey"
               options: NSKeyValueObservingOptionNew
               context: NULL];

…then, in your observer method:

-(void) observeValueForKeyPath: (NSString *)keyPath ofObject: (id) object
                        change: (NSDictionary *) change context: (void *) context
{
    BOOL newValue = [[change objectForKey: NSKeyValueChangeNewKey] boolValue];
}

Ideally you'd check whether value was nil (well, it might happen) before calling -boolValue, but that was omitted for clarity here.

like image 155
Jim Dovey Avatar answered Oct 22 '22 11:10

Jim Dovey