Skip to content

Instantly share code, notes, and snippets.

@vendruscolo
Created January 20, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendruscolo/e8b823ddf63a539c13ce to your computer and use it in GitHub Desktop.
Save vendruscolo/e8b823ddf63a539c13ce to your computer and use it in GitHub Desktop.
typedef void (^pspdf_setter)(id self, SEL _cmd, id value);
static pspdf_setter pspdf_setterForKey(NSString *key) {
return ^(id self, SEL _cmd, id value) {
// The ivar name, from the original key: fooBar -> _fooBar
// It's a convention: don't break it
const char * ivarName = [[@"_" stringByAppendingString:[key capitalizedString]] UTF8String];
// Get the ivar, so we can later replace it
Ivar ivar = class_getInstanceVariable([self class], ivarName);
id oldValue = object_getIvar(self, ivar);
// Check it's not the same
if (oldValue == value) {
return;
}
// Be KVC friently
[self willChangeValueForKey:key];
// It's different, set new value
object_setIvar(self, ivar, value);
// Be KVC friendly
[self didChangeValueForKey:key];
// Do all the common things
[self setNeedsDisplay];
};
}
+ (void)load {
someMagicMethodThatReplaceImplemenationWithBlockForKey(pspdf_setterForKey(@"radius"), @"radius");
someMagicMethodThatReplaceImplemenationWithBlockForKey(pspdf_setterForKey(@"color"), @"color");
someMagicMethodThatReplaceImplemenationWithBlockForKey(pspdf_setterForKey(@"secondaryColor"), @"secondaryColor");
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment