static void * kBackgroundColorObservationContext = &kBackgroundColorObservationContext;
[self.view addObserver:self
forKeyPath:@"backgroundColor"
options:NSKeyValueObservingOptionOld
context:kBackgroundColorObservationContext];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == kBackgroundColorObservationContext) {
/* This change is meant for us */
NSLog(@"Key changed from %@ to %@",
[change objectForKey:NSKeyValueChangeOldKey],
self.view.backgroundColor);
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)viewDidUnload {
[super viewDidUnload];
/* ... other cleanup ... */
[self.view removeObserver:self forKeyPath:@"backgroundColor"];
}
- (void)dealloc {
/* ... other cleanup ... */
[self.view removeObserver:self forKeyPath:@"backgroundColor"];
}
KVO is already supported for your own property accessors, however if you have something custom where and you need to modify values outside of property accessors, you might need to raise the KVO events so others can subscribe.
For example:
- (void)setFullName:(NSString *)newFullName {
[self willChangeValueForKey:@"firstName"];
[self willChangeValueForKey:@"lastName"];
// set ivars from newFullName
[self didChangeValueForKey:@"lastName"];
[self didChangeValueForKey:@"firstName"];
}
For more information, read this article on KVO Compliance which covers this and more approaches.