Created
August 31, 2012 14:36
-
-
Save pnc/3553719 to your computer and use it in GitHub Desktop.
PCPropertyObserver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// © 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