写在前面

runtime 是底层的东西,是 OC 的根基,叫做”动态运行时”,运行过程中将 OC 转化为 C,在程序运行时候提供服务,如果消息传递,动态添加属性,动态添加方法 以及重要的 KVC 的dictionary转 model.
程序🐶必啃的骨头,来一起下嘴,啃~~

一,使用 runtime 进行 KVC 映射赋值

KVC 的实现原理为在 model 中查找相应的方法进行赋值,顺序如下:
OC(九)-runtime机制简单理解和应用 - 图1

如果上面的图(微信随便画了一个😀)无法理解,就看下面的一幅图.由于 简书的Markdown 还不支持流程图,无法得到正常的流程图,就在别的编辑器写好,截取过来了
OC(九)-runtime机制简单理解和应用 - 图2
附上 Markdown语法如下:

明白了这个,就开始写代码.
创建 NSObject 的 Category, 定义类方法

.h

  1. //
  2. // NSObject+CategoryOfNSObject.h
  3. // Runtime
  4. //
  5. // Created by 宋金委 on 2016/10/21.
  6. // Copyright © 2016年 song. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. @interface NSObject (CategoryOfNSObject)
  10. /**
  11. 初始化一个 Model
  12. @param dict 字典
  13. */
  14. +(instancetype)initModelWithDictionary:(NSDictionary *)dict;
  15. @end

.m

  1. //
  2. // NSObject+CategoryOfNSObject.m
  3. // Runtime
  4. //
  5. // Created by 宋金委 on 2016/10/21.
  6. // Copyright © 2016年 song. All rights reserved.
  7. //
  8. #import "NSObject+CategoryOfNSObject.h"
  9. #import <objc/runtime.h>
  10. @implementation NSObject (CategoryOfNSObject)
  11. +(instancetype)initModelWithDictionary:(NSDictionary *)dict{
  12. id model = [[self alloc] init];
  13. //变量个数
  14. unsigned int numberOfVariable = 0;
  15. //成员变量的数组
  16. Ivar* ivarList = class_copyIvarList([self class], &numberOfVariable);
  17. for (int i = 0 ; i < numberOfVariable; i++) {
  18. Ivar singleVariable = ivarList[i];
  19. //成员变量类型 格式:\"type\"
  20. NSString* variableType = [NSString stringWithUTF8String:ivar_getTypeEncoding(singleVariable)];
  21. variableType = [variableType stringByReplacingOccurrencesOfString:@"@" withString:@""];
  22. variableType = [variableType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
  23. //成员变量名字 格式:_name
  24. NSString* variableName = [NSString stringWithUTF8String:ivar_getName(singleVariable)];
  25. //key "_name"-->"name"
  26. NSString* key = [variableName substringFromIndex:1];
  27. //获取字典对应 key的值
  28. id valueOfKeyInDict = dict[key];
  29. if (![valueOfKeyInDict isKindOfClass:[NSDictionary class]] && ![variableType hasPrefix:@"NS"]) {
  30. Class classOfVariable = NSClassFromString(variableType);
  31. valueOfKeyInDict = [classOfVariable initModelWithDictionary:valueOfKeyInDict];
  32. }
  33. if(valueOfKeyInDict){
  34. [model setValue:valueOfKeyInDict forKey:key];
  35. }
  36. }
  37. //很重要
  38. free(ivarList);
  39. return model;
  40. }
  41. @end

简单测试调用代码

  1. //
  2. // ViewController.m
  3. // Runtime
  4. //
  5. // Created by 宋金委 on 2016/10/20.
  6. // Copyright © 2016年 song. All rights reserved.
  7. //
  8. #import "ViewController.h"
  9. #import "NSObject+CategoryOfNSObject.h"
  10. #import "Model.h"
  11. @interface ViewController ()
  12. @end
  13. @implementation ViewController
  14. - (void)viewDidLoad {
  15. [super viewDidLoad];
  16. Model* model = [Model initModelWithDictionary:@{@"name":@"Song",@"age":@"22",@"address":@"China"}];
  17. NSLog(@"----%@",model);
  18. }
  19. @end

测试结果:
OC(九)-runtime机制简单理解和应用 - 图3

二,消息机制

在 OC中调用方法时候,是被clang 编译器 cpp,terminal可以输入 “clang -rewrite-objc 文件名”,可以生成. cpp 文件,可以看到方法调用工程中被编译为 objc_msgSend(“className”,”methodName”);

例如:只是简写过后的样子

  1. NSArray * array = [[NSArray alloc] init];
  2. //最底层的写法
  3. ==> NSArray * array = objc_msgSend(getClass("NSArray"),sel_registerName("alloc"));
  4. //另外一种方法
  5. ==> array = objc_msgSend(array,@selector(init));

应用场景:当某个方法没有暴露,可以使用 obj_msgSend 调用;
方法调用工程: 编译工程时候,会将对象的方法,转化为方法编号,放到对象的方法列表(hash 表),在方法被调用的过程中,发送消息,通过类对象的 isa 指针查找方法是否存在,如果存在,映射对应的方法编号,在代码区查找对应的实现,调用方法.

三,替换方法

  1. //
  2. // NSMutableArray+CategoryOfNSMutableArray.m
  3. // Runtime
  4. //
  5. // Created by HMC on 2016/10/24.
  6. // Copyright © 2016年 song. All rights reserved.
  7. //
  8. #import "NSMutableArray+CategoryOfNSMutableArray.h"
  9. #import <objc/runtime.h>
  10. @implementation NSMutableArray (CategoryOfNSMutableArray)
  11. //第一次加载的时候执行一次
  12. +(void)load{
  13. Method addObject = class_getInstanceMethod(self, @selector(addObject:));
  14. Method song_addObject = class_getInstanceMethod(self, @selector(song_addObject:));
  15. method_exchangeImplementations(addObject, song_addObject);
  16. }
  17. -(void)song_addObject:(id)anObject {
  18. NSLog(@"插入对象不能为空");
  19. if (anObject == nil) {
  20. NSLog(@"插入对象不能为空");
  21. }else{
  22. [self song_addObject:anObject];
  23. }
  24. }
  25. @end

调用代码,
还是按原来的方法调用,替换方法只是在分类中是系统直接替换的.

  1. NSMutableArray * ar = [NSMutableArray array];
  2. NSString * s = @"123";
  3. [ar addObject:s];

四,动态添加对象属性

其实就是在分类中重写该属性的get/set 方法,在方法中使用 runtime 添加或者获取值

  1. //
  2. // UIAlertView+CategoryOfUIAlertView.m
  3. // Runtime
  4. //
  5. // Created by 宋金委 on 2016/10/24.
  6. // Copyright © 2016年 song. All rights reserved.
  7. //
  8. #import "UIAlertView+CategoryOfUIAlertView.h"
  9. #import <objc/runtime.h>
  10. @implementation UIAlertView (CategoryOfUIAlertView)
  11. -(NSNumber *)intervalTime{
  12. return objc_getAssociatedObject(self, @"intervalTime");
  13. }
  14. -(void)setIntervalTime:(NSNumber *)intervalTime{
  15. objc_setAssociatedObject(self, @"intervalTime", intervalTime, OBJC_ASSOCIATION_ASSIGN);
  16. }
  17. @end

OC(九)-runtime机制简单理解和应用 - 图4

五,动态添加对象方法

应用场景:当一个 APP 提供增值服务,比如开通会员,可以提供会员服务,就会响应相应的方法;
实现原理: 当一个 instance 通过performSelector(methodName)方法调用methodName 时,如果检测每一个实现该方法就会执行+(BOOL)resolveInstanceMethod:(SEL)sel这个类方法,我们在此方法中运用 runtime 进行动态添加方法,反之就会 crash.

  1. //
  2. // User.m
  3. // Runtime
  4. //
  5. // Created by 宋金委 on 2016/10/24.
  6. // Copyright © 2016年 song. All rights reserved.
  7. //
  8. #import "User.h"
  9. #import <objc/runtime.h>
  10. @implementation User
  11. void VIPSeriviceImp(id self, SEL _cmd ,NSNumber* num ){
  12. NSLog(@"您开通的是%@元的 VIP",num);
  13. }
  14. +(BOOL)resolveInstanceMethod:(SEL)sel{
  15. if (sel == NSSelectorFromString(@"VIPSerivice:")) {
  16. /**
  17. runtime 动态添加方法
  18. @param self 对象本身
  19. @param sel SEL
  20. @param IMP sel 的实现(C 函数)
  21. @param string C函数格式
  22. @return BOOL
  23. */
  24. class_addMethod(self, sel, (IMP)VIPSeriviceImp, "v@:@");
  25. }
  26. return [super resolveInstanceMethod:sel];
  27. }
  28. @end

OC(九)-runtime机制简单理解和应用 - 图5
动态调用方法performSelector ,会报警告⚠️,不用管,这是编译器的代码检测功能引起的.

  1. //动态添加方法
  2. User * user = [User new];
  3. [user performSelector:@selector(VIPSerivice:) withObject:@10];

代码地址: 点这里