zoukankan      html  css  js  c++  java
  • iOS-Runtime的那些事...编辑中....

    Runtime-iOS的黑魔法,还是很好玩的,消息机制、方法替换简单记录了一点,持续更新....

    1.方法替换

    在类load方法中,替换系统方法

    + (void)load{
        
        Method oldColorMethod = class_getInstanceMethod([self class], @selector(setBackgroundColor:));
        
        Method newColorMethod = class_getInstanceMethod([self class], @selector(xg_setBackgroundColor:));
        ///交换方法
        ///调用系统的setBackgroundColor方法就会执行xg_setBackgroundColor方法
        method_exchangeImplementations(oldColorMethod, newColorMethod);
    }
    - (void)xg_setBackgroundColor:(UIColor *)color{
        ///在此方法中不要调用系统的setBackgroundColor方法,防止循环引用
        [self xg_setBackgroundColor:color];
    }

    2.动态生成属性

    - (void)setNamexg:(NSString *)namexg{
        objc_setAssociatedObject(self, "namexg", namexg, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    - (NSString *)namexg{
        return objc_getAssociatedObject(self, "namexg");
    }

     

    3.字典转模型的实现

    #import "NSObject+xgDictionary.h"
    #import <objc/runtime.h>
    
    @implementation NSObject (xgDictionary)
    + (instancetype)xg_modelKeyValues:(NSDictionary *)dicData{
        id model = [[self alloc]init];
        unsigned int count = 0;
        ///返回类的所有属性和变量
        Ivar *ivarsA = class_copyIvarList(self, &count);
        for (int i = 0; i < count; i ++) {
            Ivar iv = ivarsA[i];
            NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(iv)];
            ivarName = [ivarName substringFromIndex:1];
            id value = dicData[ivarName];
            [model setValue:value forKeyPath:ivarName];
        }
        return model;
    }
    @end
  • 相关阅读:
    mySQL安装的时候一直卡在starting server这里解决办法
    编译安装nginx
    用户访问网站原理及流程
    mysql备份及恢复
    sed
    mysql 基础
    nginx优化
    mysql 三种日志
    tr
    date
  • 原文地址:https://www.cnblogs.com/wangkejia/p/8137327.html
Copyright © 2011-2022 走看看