Observing a property of a NSObject subclass

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents