OC高效率52之理解消息转发机制

Objective-C 动态属性实现
本文介绍了一个使用 Objective-C 实现动态属性的示例。通过 EOCAutoDictionary 类展示了如何利用 runtime 动态添加属性,并实现了 setter 和 getter 方法。
#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);
}


转载于:https://my.oschina.net/u/2319073/blog/608661

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值