美文网首页
使用runtime对使用@dynamic ;属性使用访问方法

使用runtime对使用@dynamic ;属性使用访问方法

作者: guoguojianshu | 来源:发表于2019-05-04 22:05 被阅读0次
    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface SecondViewController : UIViewController
    @property (nonatomic,copy)NSString * name;
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "SecondViewController.h"
    #import <objc/runtime.h>
    @interface SecondViewController ()
    @property (nonatomic,strong)NSMutableDictionary * backingStore;
    @end
    
    @implementation SecondViewController
    @dynamic name;
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
    }
    -(instancetype)init{
        if (self = [super init]) {
            _backingStore = [NSMutableDictionary new];
        }
        return self;
    }
    +(BOOL)resolveInstanceMethod:(SEL)sel{
        NSString * selectorString = NSStringFromSelector(sel);
        if ([selectorString containsString:@"set"]) {
            class_addMethod(self, sel, (IMP)autoDictionarySetter, "v@:@");
        }else{
            class_addMethod(self, sel, (IMP)autoDictionaryGetter, "@@:");
        }
        return YES;
    }
    void autoDictionarySetter(id self ,SEL _cmd, id value){
        SecondViewController * typeSelf = (SecondViewController *)self;
       NSMutableDictionary * backingStore =  typeSelf.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];
        }
        
        
    }
    
    
    id autoDictionaryGetter (id self , SEL _cmd){
        SecondViewController * typeSelf = (SecondViewController *)self;
        NSMutableDictionary * backingStor = typeSelf.backingStore;
        NSString * key = NSStringFromSelector(_cmd);
        return [backingStor objectForKey:key];
    }
    @end
    

    使用访问器方法

      SecondViewController * vc = [[SecondViewController alloc]init];
        vc.name = @"123";
        NSLog(@"%@",vc.name);
    

    这个就是使用动态方法解析,往类中添加新的方法的实践。

    相关文章

      网友评论

          本文标题:使用runtime对使用@dynamic ;属性使用访问方法

          本文链接:https://www.haomeiwen.com/subject/awzfoqtx.html