Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.