Skip to content

Instantly share code, notes, and snippets.

@pnc
Created August 31, 2012 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pnc/3553719 to your computer and use it in GitHub Desktop.
Save pnc/3553719 to your computer and use it in GitHub Desktop.
PCPropertyObserver
// © 2011 Phillip N. Calvin
// For use in a setter.
// Signs up self to receive KVO notifications about given properties
// on any new value and removes self as an observer from the old value.
// For example, to observe properties of a property called customer
// (backed by ivar _customer):
// PCPropertyObserver(customer, @"allowSubscriptionPurchase", @"availableProducts");
// You'd need to write this selector yourself:
// - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
// if ([keyPath isEqualToString:@"availableProducts"] ||
// [keyPath isEqualToString:@"allowSubscriptionPurchase"]) {
// // Handle change to key
// }
// }
#define PCPropertyObserverWithFlags(property, flags, args...) \
NSArray *observedProperties = [NSArray arrayWithObjects:args, nil]; \
if (_ ## property != nil) { \
for (NSString *key in observedProperties) { \
[_ ## property removeObserver:self forKeyPath:key]; \
} \
} \
_ ## property = property; \
if (property != nil) { \
for (NSString *key in observedProperties) { \
[property addObserver:self forKeyPath:key options:flags context:nil]; \
} \
}
#define PCPropertyObserver(property, args...) \
PCPropertyObserverWithFlags(property, NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial, args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment