Created
April 23, 2012 05:41
-
-
Save alexdrone/2469000 to your computer and use it in GitHub Desktop.
@dynamic implementation
This file contains 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
Person.h (Person) | |
@interface Person : NSObject | |
@property (copy) NSString *givenName; | |
@property (copy) NSString *surname; | |
@end | |
Person.m (Person) | |
@interface Person () | |
@property (strong) NSMutableDictionary *properties; | |
@end | |
@implementation Person | |
@dynamic givenName, surname; | |
@synthesize properties = properties_; | |
- (id)init { | |
if ((self = [super init])) { | |
properties_ = [[NSMutableDictionary alloc] init]; | |
} | |
return self; | |
} | |
static id propertyIMP(id self, SEL _cmd) { | |
return [[self properties] valueForKey: | |
NSStringFromSelector(_cmd)]; | |
} | |
static void setPropertyIMP(id self, SEL _cmd, id aValue) { | |
id value = [aValue copy]; | |
NSMutableString *key = | |
[NSStringFromSelector(_cmd) mutableCopy]; | |
// Delete “set” and “:” and lowercase first letter | |
[key deleteCharactersInRange:NSMakeRange(0, 3)]; | |
[key deleteCharactersInRange: | |
NSMakeRange([key length] - 1, 1)]; | |
NSString *firstChar = [key substringToIndex:1]; | |
[key replaceCharactersInRange:NSMakeRange(0, 1) | |
withString:[firstChar lowercaseString]]; | |
[[self properties] setValue:value forKey:key]; | |
} | |
+ (BOOL)resolveInstanceMethod:(SEL)aSEL { | |
if ([NSStringFromSelector(aSEL) hasPrefix:@”set”]) { | |
class_addMethod([self class], aSEL,(IMP)setPropertyIMP, “v@:@”); | |
} | |
else { | |
class_addMethod([self class], aSEL, (IMP)propertyIMP, “@@:”); | |
} | |
return YES; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment