#pragma mark 演示动态方法解析
#import <Foundation/Foundation.h>
@interface EOCAutoDictionary : NSObject
@property (nonatomic ,strong) NSString *string;
@property (nonatomic ,strong) NSNumber *number;
@property (nonatomic ,strong) NSDate *date;
@property (nonatomic ,strong) id opaqueObject;
@end
#import "EOCAutoDictionary.h"
#import <objc/runtime.h>
@interface EOCAutoDictionary()
@property (nonatomic ,strong) NSMutableDictionary *backingStore;
@end
@implementation EOCAutoDictionary
//声明@dynamic 编译器就不会自动为其生成实例变量及存取方法
@dynamic string , number , date , opaqueObject;
-(id)init
{
if (self = [super init])
{
_backingStore = [NSMutableDictionary new];
}
return self;
}
id autoDictionaryGetter(id self ,SEL _cmd){
EOCAutoDictionary *typedSelf = (EOCAutoDictionary*)self;
NSMutableDictionary *backingStore = typedSelf.backingStore;
NSString *key = NSStringFromSelector(_cmd);
return [backingStore objectForKey:key];
}
void autoDictionarySetter(id self , SEL _cmd,id value){
EOCAutoDictionary *typedSelf = (EOCAutoDictionary*)self;
NSMutableDictionary *backingStore = typedSelf.backingStore;
NSString *selectorString = NSStringFromSelector(_cmd);
NSMutableString *key = [selectorString mutableCopy];
[key deleteCharactersInRange:NSMakeRange(key.length-1, 1)];
[key deleteCharactersInRange:NSMakeRange(0, 3)];
NSString *lowercaseFirstChar = [[key substringToIndex:1] lowercaseString];
[key replaceCharactersInRange:NSMakeRange(0, 1) withString:lowercaseFirstChar];
if (value){
[backingStore setObject:value forKey:key];
}
else{
[backingStore removeObjectForKey:key];
}
}
+(BOOL)resolveInstanceMethod:(SEL)sel
{
NSString *selectorString = NSStringFromSelector(sel);
if ([selectorString hasPrefix:@"set"])
{
class_addMethod(self, sel, (IMP)autoDictionarySetter, "v@:@");
}else{
class_addMethod(self, sel, (IMP)autoDictionaryGetter, "@@:");
}
return YES;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
EOCAutoDictionary *dict = [EOCAutoDictionary new];
dict.date = [NSDate dateWithTimeIntervalSince1970:475372800];
NSLog(@"%@",dict.date);
}