Observing a property of an NSObject subclass
suggest changeMost 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 is called when accessing the @"firstName" key path, whether or not a _firstName instance variable or a setFirstName setter exists. Assigning the instance variable directly does not notify observers unless the code also calls willChangeValueForKey: and didChangeValueForKey:. Remove the observer before it is deallocated. A nil context cannot tell this registration apart from one a superclass added.