写在前面
runtime 是底层的东西,是 OC 的根基,叫做”动态运行时”,运行过程中将 OC 转化为 C,在程序运行时候提供服务,如果消息传递,动态添加属性,动态添加方法 以及重要的 KVC 的dictionary转 model.
程序🐶必啃的骨头,来一起下嘴,啃~~
一,使用 runtime 进行 KVC 映射赋值
KVC 的实现原理为在 model 中查找相应的方法进行赋值,顺序如下:

如果上面的图(微信随便画了一个😀)无法理解,就看下面的一幅图.由于 简书的Markdown 还不支持流程图,无法得到正常的流程图,就在别的编辑器写好,截取过来了

附上 Markdown语法如下:
明白了这个,就开始写代码.
创建 NSObject 的 Category, 定义类方法
.h
//// NSObject+CategoryOfNSObject.h// Runtime//// Created by 宋金委 on 2016/10/21.// Copyright © 2016年 song. All rights reserved.//#import <Foundation/Foundation.h>@interface NSObject (CategoryOfNSObject)/**初始化一个 Model@param dict 字典*/+(instancetype)initModelWithDictionary:(NSDictionary *)dict;@end
.m
//// NSObject+CategoryOfNSObject.m// Runtime//// Created by 宋金委 on 2016/10/21.// Copyright © 2016年 song. All rights reserved.//#import "NSObject+CategoryOfNSObject.h"#import <objc/runtime.h>@implementation NSObject (CategoryOfNSObject)+(instancetype)initModelWithDictionary:(NSDictionary *)dict{id model = [[self alloc] init];//变量个数unsigned int numberOfVariable = 0;//成员变量的数组Ivar* ivarList = class_copyIvarList([self class], &numberOfVariable);for (int i = 0 ; i < numberOfVariable; i++) {Ivar singleVariable = ivarList[i];//成员变量类型 格式:\"type\"NSString* variableType = [NSString stringWithUTF8String:ivar_getTypeEncoding(singleVariable)];variableType = [variableType stringByReplacingOccurrencesOfString:@"@" withString:@""];variableType = [variableType stringByReplacingOccurrencesOfString:@"\"" withString:@""];//成员变量名字 格式:_nameNSString* variableName = [NSString stringWithUTF8String:ivar_getName(singleVariable)];//key "_name"-->"name"NSString* key = [variableName substringFromIndex:1];//获取字典对应 key的值id valueOfKeyInDict = dict[key];if (![valueOfKeyInDict isKindOfClass:[NSDictionary class]] && ![variableType hasPrefix:@"NS"]) {Class classOfVariable = NSClassFromString(variableType);valueOfKeyInDict = [classOfVariable initModelWithDictionary:valueOfKeyInDict];}if(valueOfKeyInDict){[model setValue:valueOfKeyInDict forKey:key];}}//很重要free(ivarList);return model;}@end
简单测试调用代码
//// ViewController.m// Runtime//// Created by 宋金委 on 2016/10/20.// Copyright © 2016年 song. All rights reserved.//#import "ViewController.h"#import "NSObject+CategoryOfNSObject.h"#import "Model.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];Model* model = [Model initModelWithDictionary:@{@"name":@"Song",@"age":@"22",@"address":@"China"}];NSLog(@"----%@",model);}@end
测试结果:

二,消息机制
在 OC中调用方法时候,是被clang 编译器 cpp,terminal可以输入 “clang -rewrite-objc 文件名”,可以生成. cpp 文件,可以看到方法调用工程中被编译为 objc_msgSend(“className”,”methodName”);
例如:只是简写过后的样子
NSArray * array = [[NSArray alloc] init];//最底层的写法==> NSArray * array = objc_msgSend(getClass("NSArray"),sel_registerName("alloc"));//另外一种方法==> array = objc_msgSend(array,@selector(init));
应用场景:当某个方法没有暴露,可以使用 obj_msgSend 调用;
方法调用工程: 编译工程时候,会将对象的方法,转化为方法编号,放到对象的方法列表(hash 表),在方法被调用的过程中,发送消息,通过类对象的 isa 指针查找方法是否存在,如果存在,映射对应的方法编号,在代码区查找对应的实现,调用方法.
三,替换方法
//// NSMutableArray+CategoryOfNSMutableArray.m// Runtime//// Created by HMC on 2016/10/24.// Copyright © 2016年 song. All rights reserved.//#import "NSMutableArray+CategoryOfNSMutableArray.h"#import <objc/runtime.h>@implementation NSMutableArray (CategoryOfNSMutableArray)//第一次加载的时候执行一次+(void)load{Method addObject = class_getInstanceMethod(self, @selector(addObject:));Method song_addObject = class_getInstanceMethod(self, @selector(song_addObject:));method_exchangeImplementations(addObject, song_addObject);}-(void)song_addObject:(id)anObject {NSLog(@"插入对象不能为空");if (anObject == nil) {NSLog(@"插入对象不能为空");}else{[self song_addObject:anObject];}}@end
调用代码,
还是按原来的方法调用,替换方法只是在分类中是系统直接替换的.
NSMutableArray * ar = [NSMutableArray array];NSString * s = @"123";[ar addObject:s];
四,动态添加对象属性
其实就是在分类中重写该属性的get/set 方法,在方法中使用 runtime 添加或者获取值
//// UIAlertView+CategoryOfUIAlertView.m// Runtime//// Created by 宋金委 on 2016/10/24.// Copyright © 2016年 song. All rights reserved.//#import "UIAlertView+CategoryOfUIAlertView.h"#import <objc/runtime.h>@implementation UIAlertView (CategoryOfUIAlertView)-(NSNumber *)intervalTime{return objc_getAssociatedObject(self, @"intervalTime");}-(void)setIntervalTime:(NSNumber *)intervalTime{objc_setAssociatedObject(self, @"intervalTime", intervalTime, OBJC_ASSOCIATION_ASSIGN);}@end

五,动态添加对象方法
应用场景:当一个 APP 提供增值服务,比如开通会员,可以提供会员服务,就会响应相应的方法;
实现原理: 当一个 instance 通过performSelector(methodName)方法调用methodName 时,如果检测每一个实现该方法就会执行+(BOOL)resolveInstanceMethod:(SEL)sel这个类方法,我们在此方法中运用 runtime 进行动态添加方法,反之就会 crash.
//// User.m// Runtime//// Created by 宋金委 on 2016/10/24.// Copyright © 2016年 song. All rights reserved.//#import "User.h"#import <objc/runtime.h>@implementation Uservoid VIPSeriviceImp(id self, SEL _cmd ,NSNumber* num ){NSLog(@"您开通的是%@元的 VIP",num);}+(BOOL)resolveInstanceMethod:(SEL)sel{if (sel == NSSelectorFromString(@"VIPSerivice:")) {/**runtime 动态添加方法@param self 对象本身@param sel SEL@param IMP sel 的实现(C 函数)@param string C函数格式@return BOOL*/class_addMethod(self, sel, (IMP)VIPSeriviceImp, "v@:@");}return [super resolveInstanceMethod:sel];}@end

动态调用方法performSelector ,会报警告⚠️,不用管,这是编译器的代码检测功能引起的.
//动态添加方法User * user = [User new];[user performSelector:@selector(VIPSerivice:) withObject:@10];
代码地址: 点这里
