runtime那些事儿(消息机制)
创始人
2025-01-27 15:00:32
0次

[[163324]]

一、关于runtime

之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtime黑魔法的强大,趁现在有机会分享一下对runtime的一些理解。在对象调用方法是Objective-C中经常使用的功能,也就是消息的传递,而Objective-C是C的超集,所以和C不同的是,Objective-C使用的是动态绑定,也就是runtime。Objective-C的消息传递和消息机制也就不多说了,今天主要说的是动态方法,也就是函数的调用。

二、相关的几个函数

下面一张图详细的概括了每个函数调用的先后以及执行的前提

 

消息传递函数的调用

1.对象在收到无法解读的消息后,首先会调用所属类的

  1. + (BOOL)resolveInstanceMethod:(SEL)sel 

这个方法在运行时,没有找到SEL的IML时就会执行。这个函数是给类利用class_addMethod添加函数的机会。根据文档,如果实现了添加函数代码则返回YES,未实现返回NO。举个例子,新建了一个工程,首先我在ViewController这个类中执行doSomething1这个方法,代码如下

  1. // 
  2. //  ViewController.m 
  3. //  RuntimeTest1 
  4. // 
  5. //  Created by HenryCheng on 15/12/24. 
  6. //  Copyright ?(版权符号) 2015年 www.igancao.com  All rights reserved. 
  7. // 
  8.   
  9. #import "ViewController.h" 
  10.   
  11. @interface ViewController () 
  12.   
  13. @end 
  14.   
  15. @implementation ViewController 
  16.   
  17. - (void)viewDidLoad { 
  18.     [super viewDidLoad]; 
  19.     [self performSelector:@selector(doSomething)]; 
  20. } 
  21.   
  22. - (void)didReceiveMemoryWarning { 
  23.     [super didReceiveMemoryWarning]; 
  24.     // Dispose of any resources that can be recreated. 
  25. } 
  26.   
  27. @end 

运行结果

  1. **2015-12-24 10:35:37.726 RuntimeTest1[1877:337842] -[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680** 
  2. **2015-12-24 10:35:37.729 RuntimeTest1[1877:337842] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680'** 
  3. ***** First throw call stack:** 

不出意外,程序崩溃,因为没有找到doSomething这个方法,下面我们在里面实现 + (BOOL)resolveInstanceMethod:(SEL)sel这个方法,并且判断如果SEL 是doSomething那就输出add method here

  1. // 
  2. //  ViewController.m 
  3. //  RuntimeTest1 
  4. // 
  5. //  Created by HenryCheng on 15/12/24. 
  6. //  Copyright ?(版权符号) 2015年 www.igancao.com All rights reserved. 
  7. // 
  8.   
  9. #import "ViewController.h" 
  10.   
  11. @interface ViewController () 
  12.   
  13. @end 
  14.   
  15. @implementation ViewController 
  16.   
  17. - (void)viewDidLoad { 
  18.     [super viewDidLoad]; 
  19.     [self performSelector:@selector(doSomething)]; 
  20. } 
  21.   
  22. + (BOOL)resolveInstanceMethod:(SEL)sel { 
  23.     if (sel == @selector(doSomething)) { 
  24.         NSLog(@"add method here"); 
  25.         return YES; 
  26.     } 
  27.     return [super resolveInstanceMethod:sel]; 
  28. } 
  29.   
  30. - (void)didReceiveMemoryWarning { 
  31.     [super didReceiveMemoryWarning]; 
  32.     // Dispose of any resources that can be recreated. 
  33. } 
  34.   
  35. @end 

继续运行,然后看到log

  1. **2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] add method here** 
  2. **2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] -[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0** 
  3. **2015-12-24 10:47:24.690 RuntimeTest1[2007:382077] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0'** 
  4. ***** First throw call stack:** 

可以看到程序依然是崩溃了,但是我们可以看到输出了add method here,这说明我们 + (BOOL)resolveInstanceMethod:(SEL)sel这个方法执行了,并进入了判断,所以,在这儿,我们可以做一下操作,使这个方法得到相应,不至于走到***- (void)doesNotRecognizeSelector:(SEL)aSelector这个方法中而崩掉了,接下来,我么继续操作,如下

  1. // 
  2. //  ViewController.m 
  3. //  RuntimeTest1 
  4. // 
  5. //  Created by HenryCheng on 15/12/24. 
  6. //  Copyright ?(版权符号) 2015年 www.igancao.com All rights reserved. 
  7. // 
  8.   
  9. #import "ViewController.h" 
  10.   
  11. #import [objc/runtime.h](因识别问题,此处将尖括号改为方括号) 
  12.   
  13. @interface ViewController () 
  14.   
  15. @end 
  16.   
  17. @implementation ViewController 
  18.   
  19. - (void)viewDidLoad { 
  20.     [super viewDidLoad]; 
  21.     [self performSelector:@selector(doSomething)]; 
  22. } 
  23.   
  24. + (BOOL)resolveInstanceMethod:(SEL)sel { 
  25.     if (sel == @selector(doSomething)) { 
  26.         NSLog(@"add method here"); 
  27.         class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:"); 
  28.         return YES; 
  29.     } 
  30.     return [super resolveInstanceMethod:sel]; 
  31. } 
  32. void dynamicMethodIMP (id self, SEL _cmd) { 
  33.     NSLog(@"doSomething SEL"); 
  34. } 
  35.   
  36. - (void)didReceiveMemoryWarning { 
  37.     [super didReceiveMemoryWarning]; 
  38.     // Dispose of any resources that can be recreated. 
  39. } 
  40.   
  41. @end 

导入了并且在+ (BOOL)resolveInstanceMethod:(SEL)sel中执行了class_addMethod这个方法,然后定义了一个void dynamicMethodIMP (id self, SEL _cmd)这个函数,运行工程,看log

  1. **2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] add method here** 
  2. **2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] doSomething SEL** 

这时候我们发现,程序并没有崩溃,而且还输出了doSomething SEL,这时候就说明我们已经通过runtime成功的向我们这个类中添加了一个方法。关于class_addMethod这个方法,是这样定义的

  • cls   在这个类中添加方法,也就是方法所添加的类

  • name  方法名,这个可以随便起的

  • imp   实现这个方法的函数

  • types 定义该数返回值类型和参数类型的字符串,这里比如"v@:",其中v就是void,带表返回类型就是空,@代表参数,这里指的是id(self),这里:指的是方法SEL(_cmd),比如我再定义一个函数

  1. int newMethod (id self, SEL _cmd, NSString *str) { 
  2.   
  3.   return 100; 
  4. } 

那么添加这个函数的方法就应该是ass_addMethod([self class], @selector(newMethod), (IMP)newMethod, "i@:@");

2.如果在+ (BOOL)resolveInstanceMethod:(SEL)sel中没有找到或者添加方法

消息继续往下传递到- (id)forwardingTargetForSelector:(SEL)aSelector看看是不是有对象可以执行这个方法,我们来重新建个工程,然后新建一个叫SecondViewController的类,里面有一个- (void)secondVCMethod方法,如下

  1. // 
  2. //  SecondViewController.m 
  3. //  RuntimeTest2 
  4. // 
  5. //  Created by HenryCheng on 15/12/24. 
  6. //  Copyright ?(版权符号) 2015年  www.igancao.com All rights reserved. 
  7. // 
  8.   
  9. #import "SecondViewController.h" 
  10.   
  11. @interface SecondViewController () 
  12.   
  13. @end 
  14.   
  15. @implementation SecondViewController 
  16.   
  17. - (void)viewDidLoad { 
  18.     [super viewDidLoad]; 
  19.     // Do any additional setup after loading the view. 
  20. } 
  21.   
  22. - (void)secondVCMethod { 
  23.     NSLog(@"This is secondVC method !"); 
  24. } 
  25.   
  26. - (void)didReceiveMemoryWarning { 
  27.     [super didReceiveMemoryWarning]; 
  28.     // Dispose of any resources that can be recreated. 
  29. } 
  30.   
  31. /* 
  32. #pragma mark - Navigation 
  33.   
  34. // In a storyboard-based application, you will often want to do a little preparation before navigation 
  35. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
  36.     // Get the new view controller using [segue destinationViewController]. 
  37.     // Pass the selected object to the new view controller. 
  38. } 
  39. */ 
  40.   
  41. @end 

工程结构应该是这样的

工程目录图

现在我想在ViewController中调用- (void)secondVCMethod这个方法,我们知道ViewController和SecondViewController并无继承关系,按照正常的步骤去做程序肯定会因为在ViewController找不到- (void)secondVCMethod这个方法而直接崩溃的

  1. // 
  2. //  ViewController.m 
  3. //  RuntimeTest2 
  4. // 
  5. //  Created by HenryCheng on 15/12/24. 
  6. //  Copyright ?(版权符号) 2015年 www.igancao.com  All rights reserved. 
  7. // 
  8.   
  9. #import "ViewController.h" 
  10. #import @interface ViewController () 
  11.   
  12. @end 
  13.   
  14. @implementation ViewController 
  15.   
  16. - (void)viewDidLoad { 
  17.     [super viewDidLoad]; 
  18.      [self performSelector:@selector(secondVCMethod)]; 
  19. } 
  20.   
  21. - (void)didReceiveMemoryWarning { 
  22.     [super didReceiveMemoryWarning]; 
  23.     // Dispose of any resources that can be recreated. 
  24. } 
  25.   
  26. @end 

运行结果

  1. **2015-12-24 13:54:44.314 RuntimeTest2[3164:835814] -[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10** 
  2. **2015-12-24 13:54:44.317 RuntimeTest2[3164:835814] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10'** 
  3. ***** First throw call stack:** 

现在我们来处理一下这个消息,如下

  1. // 
  2. //  ViewController.m 
  3. //  RuntimeTest2 
  4. // 
  5. //  Created by HenryCheng on 15/12/24. 
  6. //  Copyright ?(版权符号) 2015年 www.igancao.com All rights reserved. 
  7. // 
  8.   
  9. #import "ViewController.h" 
  10. #import @interface ViewController () 
  11.   
  12. @end 
  13.   
  14. @implementation ViewController 
  15.   
  16. - (void)viewDidLoad { 
  17.     [super viewDidLoad]; 
  18.      [self performSelector:@selector(secondVCMethod)]; 
  19. } 
  20.   
  21. - (id)forwardingTargetForSelector:(SEL)aSelector { 
  22.     Class class = NSClassFromString(@"SecondViewController"); 
  23.     UIViewController *vc = class.new; 
  24.     if (aSelector == NSSelectorFromString(@"secondVCMethod")) { 
  25.         NSLog(@"secondVC do this !"); 
  26.         return vc; 
  27.     } 
  28.       
  29.     return nil; 
  30. } 
  31.   
  32. + (BOOL)resolveInstanceMethod:(SEL)sel { 
  33.   
  34.     return [super resolveInstanceMethod:sel]; 
  35. } 
  36.   
  37. - (void)didReceiveMemoryWarning { 
  38.     [super didReceiveMemoryWarning]; 
  39.     // Dispose of any resources that can be recreated. 
  40. } 
  41. @end 

运行结果

  1. **2015-12-24 14:00:34.168 RuntimeTest2[3284:870957] secondVC do this !** 
  2. **2015-12-24 14:00:34.169 RuntimeTest2[3284:870957] This is secondVC method !** 

我们会发现- (void)secondVCMethod这个方法执行了,程序也并没有崩溃,原因就是在这一步

  1. - (id)forwardingTargetForSelector:(SEL)aSelector { 
  2.     Class class = NSClassFromString(@"SecondViewController"); 
  3.     UIViewController *vc = class.new; 
  4.     if (aSelector == NSSelectorFromString(@"secondVCMethod")) { 
  5.         NSLog(@"secondVC do this !"); 
  6.         return vc; 
  7.     } 
  8.       
  9.     return nil; 
  10. } 

在没有找到- (void)secondVCMethod这个方法的时候,消息继续传递,直到- (id)forwardingTargetForSelector:(SEL)aSelector,然后我在里面创建了一个SecondViewController的对象,并且判断如过有这个方法,就返回SecondViewController的对象。这个函数就是消息的转发,在这儿我们成功的把消息传给了SecondViewController,然后让它来执行,所以就执行了那个方法。同时,也相当于完成了一个多继承!

三、***一点

当然,还有好几个函数,在上面那张图里面已经清晰的表达了,有兴趣的可以自己试试,看看消息的传递顺序到底是怎么样的。上面提到的这些知识runtime的冰山一角,runtime黑魔法的强大远不止于此,比如方法的调配(Method Swizzling)等,在项目实战中还是很有用的,后面有时间会再介绍.

参考

  • Objective-C Runtime  Reference

  • Objective-C Runtime Programming Guide

相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
粉嫩如何诠释霸道 东芝M805... “霸道粉”是个什么玩意东芝M805拿过来的时候,笔者扑哧笑了,不是笑这款笔记本,而是笑这款产品的颜色...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
只需三步,让你掌握阿尔法路由器... 请参照以下阿尔法路由器设置方法,通过浏览器进入及设置宽带路由器。经过这三个步骤的设置,基本上能够熟悉...
如何更省钱? 近期特价热门硒鼓... 如今激光打印设备已经成为商务或企业的绝对主力办公设备,但采购者往往忽视了激光打印设备所用的耗材,相对...
全面诠释网络负载均衡 负载均衡的出现大大缓解了服务器的压力,更是有效的利用了资源,提高了效率。那么我们现在来说一下网络负载...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...