Search code examples
objective-ckey-value-observing

when to use KVO?


I have read many docs on KVO, but I'm still confused as to when to use it.

In case objA wants to monitor a certain property of objB, like so:

self.objB = [[ObjB alloc] init];
[self.objB addObserver:self
            forKeyPath:@"address"
               options:0
               context:nil];

so if objB's property changes, and it can only be changed by self, why not just do this:

self.objB.property = @"newValue";
[self doSomethingBasedOnNewValueOfObjBnewProperty];

instead of

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

{
    if(keyPath == @"address") {
        [self doSomethingBasedOnNewValueOfObjBnewProperty];
    }
}

It may be useful when used with a singleton, like self.objB = [ObjB sharedInstance], where properties may be changed by other objects. Is this the only use case?


Solution

  • Not all instances of all classes are created and edited only by the same instance (which is effectively what your example indicates).

    KVO is a generic method by which one instance can observe changes on another and receive notifications of what has happened. Those changes could be triggered from anywhere.

    Say you added a 3rd party library to your project. You don't know how it's implemented. Calling one method could change multiple different properties in the library class instance. KVO provides an easy way for you to monitor and react to those changes.

    KVO also supplies 'Dependent Keys' which allows you to configure relationships between keys so you can say "the value of this property depends on that of one or more other attributes in another object" and KVO will tell you when it happens. This could be particularly useful in a managed object subclass say, if you have a transient key that holds a cached value for some persistent key and the cache needs to be updated whenever the persistent value changes...