iOS Key Value Coding-Key Value Observation Observing a property of a NSObject subclass

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Most KVO and KVC functionality is already implemented by default on all NSObject subclasses.

To start observing a property named firstName of an object named personObject do this in the observing class:

[personObject addObserver:self
               forKeyPath:@"firstName"
                  options:NSKeyValueObservingOptionNew
                  context:nil];

The object that self in the above code refers to will then receive a observeValueForKeyPath:ofObject:change:context: message whenever the observed key path changes.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context
{
    NSLog(@"new value of %@ is: %@", keyPath, change[NSKeyValueChangeNewKey]);
}

"Key path" is a KVC term. NSObject subclasses implement KVC functionality by default.

An instance variable named _firstName will be accessible by the @"firstName" key path.

A getter method named firstName will be called when accessing the @"firstName" key path, regardless of there being a _firstName instance variable or setFirstName setter method.



Got any iOS Question?