美文网首页iOS工作系列OC语法iOS精华
runtime那些事(消息机制)

runtime那些事(消息机制)

作者: HenryCheng | 来源:发表于2015-12-24 16:56 被阅读6068次

一、关于runtime


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

二、相关的几个函数


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

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

+ (BOOL)resolveInstanceMethod:(SEL)sel

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

//
//  ViewController.m
//  RuntimeTest1
//
//  Created by HenryCheng on 15/12/24.
//  Copyright © 2015年 www.igancao.com  All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end ```
运行结果

2015-12-24 10:35:37.726 RuntimeTest1[1877:337842] -[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680
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'
***** First throw call stack:**

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

//
// ViewController.m
// RuntimeTest1
//
// Created by HenryCheng on 15/12/24.
// Copyright © 2015年 www.igancao.com All rights reserved.
//

import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];

}

  • (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(doSomething)) {
    NSLog(@"add method here");
    return YES;
    }
    return [super resolveInstanceMethod:sel];
    }
  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

@end```
继续运行,然后看到log

**2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] add method here**
**2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] -[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0**
**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'**
***** First throw call stack:**   

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

//
//  ViewController.m
//  RuntimeTest1
//
//  Created by HenryCheng on 15/12/24.
//  Copyright © 2015年 www.igancao.com All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];

}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(doSomething)) {
        NSLog(@"add method here");
        class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}
void dynamicMethodIMP (id self, SEL _cmd) {
    
    NSLog(@"doSomething SEL");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

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

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

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

OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp,  const char *types)
  • cls 在这个类中添加方法,也就是方法所添加的类
  • name 方法名,这个可以随便起的
  • imp 实现这个方法的函数
  • types定义该数返回值类型和参数类型的字符串,这里比如"v@:",其中v就是void,带表返回类型就是空,@代表参数,这里指的是id(self),这里:指的是方法SEL(_cmd),比如我再定义一个函数
int newMethod (id self, SEL _cmd, NSString *str) {
    
    return 100;
}

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

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

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

//
//  SecondViewController.m
//  RuntimeTest2
//
//  Created by HenryCheng on 15/12/24.
//  Copyright © 2015年  www.igancao.com All rights reserved.
//

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)secondVCMethod {
    
    NSLog(@"This is secondVC method !");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

工程结构应该是这样的

工程目录图
现在我想在ViewController中调用- (void)secondVCMethod这个方法,我们知道ViewControllerSecondViewController并无继承关系,按照正常的步骤去做程序肯定会因为在ViewController找不到- (void)secondVCMethod这个方法而直接崩溃的
//
//  ViewController.m
//  RuntimeTest2
//
//  Created by HenryCheng on 15/12/24.
//  Copyright © 2015年 www.igancao.com  All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self performSelector:@selector(secondVCMethod)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

运行结果

**2015-12-24 13:54:44.314 RuntimeTest2[3164:835814] -[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10**
**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'**
***** First throw call stack:**

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

//
//  ViewController.m
//  RuntimeTest2
//
//  Created by HenryCheng on 15/12/24.
//  Copyright © 2015年 www.igancao.com All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self performSelector:@selector(secondVCMethod)];
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    Class class = NSClassFromString(@"SecondViewController");
    UIViewController *vc = class.new;
    if (aSelector == NSSelectorFromString(@"secondVCMethod")) {
        NSLog(@"secondVC do this !");
        return vc;
    }
    
    return nil;
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {

    return [super resolveInstanceMethod:sel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

运行结果

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

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

- (id)forwardingTargetForSelector:(SEL)aSelector {
    Class class = NSClassFromString(@"SecondViewController");
    UIViewController *vc = class.new;
    if (aSelector == NSSelectorFromString(@"secondVCMethod")) {
        NSLog(@"secondVC do this !");
        return vc;
    }
    
    return nil;
}

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

三、最后一点


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

参考

相关文章

  • Runtime那些事儿(消息机制)

    Runtime那些事儿(消息机制) Runtime那些事儿(消息机制)

  • runtime那些事(消息机制)

    一、关于runtime 之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtim...

  • Runtime 的应用

    前面我们说到:Runtime 消息传递机制Runtime 消息转发机制Runtime 交换方法今天我们来谈谈Run...

  • iOS runtime

    runtime 是 oc 语音的基础首先runtime的核心机制是消息机制 也就是oc的消息机制首先oc的消息机制...

  • iOS - Runtime - 概念和方法交换

    runtime的概述runtime的相关概念runtime消息机制消息传递动态方法解析消息转发runtime的作用...

  • 深入浅出Runtime

    Runtime运行时 目录 一、runtime 简介二、消息机制<了解>2.1 消息机制原理2.2 消息调用流程三...

  • Runtime补救措施

    原文地址 :Runtime那些事儿(消息机制) 总结:当找不到对应的IML方法时,RunTime会尝试通过用户设定...

  • Runtime那些事儿(消息机制)

    一、关于runtime 之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtim...

  • Runtime那些事儿(消息机制)

    一、关于runtime 之前在项目中有遇到过用runtime解决改变全局字体的问题,所以再一次感受到了runtim...

  • IOS开发谈谈对Runtime 和 Runloop的理解

    Runtime Runtime简称运行时,OC就是运行时机制,也就是在运行时候的一些机制,其中最重要的事消息机制。...

网友评论

  • PGOne爱吃饺子:当然你的那个换字体的博客我已经看了,请问还有其他的列子么
  • PGOne爱吃饺子:楼主,后面说了一句话,说runtime在项目中有很大的用处,楼主可以举几个列子么,🙏🙏
  • 水田夏木:值得参考
  • DSperson:每次忘了都来翻一遍
    DSperson:@HenryCheng 我今天尝试了一下"i@:@"这个参数 我这么写方法是

    + (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(doSomething)) {
    class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "i@:@");
    return true;
    }
    return [super resolveInstanceMethod:sel];
    }

    int dynamicMethodIMP(id self, SEL _cmd, NSString * du) {
    NSLog(@"doSomething SEL");
    return 100;
    }
    内存泄漏了为什么呢?
    HenryCheng:@Ds_Run :smile::smile::smile:
  • 是我始终拒绝成长吗:iml是什么?是imp吗
    HenryCheng:@是我始终拒绝成长吗 额,是的,写错了
  • smirkk:为什么增加了class_addMethod([self class], @selector(newMethod), (IMP)newMethod, "i@:@");要报错呢?
  • dc2cb82b2c13:forwardingTargetForSelector 在这个方法里面千万不能返回self。会死循环的。
    图中可能写错了。
    @HenryCheng
  • Raybon_lee:按照你的设计实现完了 :smile:
    Raybon_lee:@HenryCheng 你试过用hook 的方式进行方法替换么,我好想弄错了什么,我对NSObject 写了一个分类,出现了一点问题,本来想着方法替换呢,结果识别不到,不知道什么原因
    HenryCheng:@Raybon_lee :blush::blush:
  • DSperson:明白了一些 牛
  • jiang12306:👍🏻
  • d28645104c16:666,一直想学这东西,但是搜出来的都是文字介绍,一遍一遍的搞不懂。:joy_cat:
    HenryCheng:@ios雪松 对你有帮助就好,喜欢的话就star一下吧
  • 呵呵x3:楼主,有错别字哦 ,不过依然很赞
    HenryCheng:@会敲代码的iOS汪 :joy: :joy: :joy: ,可能打字的时候比较急,没注意,下次注意,谢谢包含
  • CarryIT:写的很棒,赞:+1:🏻
    HenryCheng:@ACoderiOS 谢谢支持🙏
  • 5e17e4fdf014:mark……很棒的分享
    HenryCheng:@5e17e4fdf014 谢谢支持
  • 卖艺小青年o0:学习了不少
    HenryCheng:@0a0c099838da 有帮助就好
  • 苦笑男神:非常不错!!学习了,谢谢博主!:heart_eyes:
    HenryCheng:@日月神话的爱 :pray:
  • 卓无尘:图可以更详细点,还有方法缓存和寻找父类中方法。好像还有retain,release,autorelease,retainCount方法返回self,不过这是在垃圾收集环境中的。 另外详细点说图中的那个返回NSMethodSignature是为了构建一个NSInvocation.然后传递给forwardInvocation使用。非常感谢分享。
    HenryCheng:@卓无尘 嗯,是的,消息的全部转发这儿还没说到
  • 581628cbdc3f:这什么语言,,,
    HenryCheng:@581628cbdc3f 👏👏👏
    581628cbdc3f:@HenryCheng 只会c++:joy_cat:
    HenryCheng:@581628cbdc3f OC啊。。。。。。
  • 6de54c2e26a0::+1::+1::+1:虽然看的不是很懂,还是要赞,收藏先:smile::smile:
    HenryCheng:@张文生action 有问题可以交流:blush::blush::blush:
  • __Null:很不错的呢 mark一下
    HenryCheng:@iOSTracker :blush::blush::blush:
  • Easy_VO:楼主啊,可以用runtime 统一页面字体颜色吗
    HenryCheng:@0f93bcef3fa2 最近在忙着上版本呢,博客好久没更新了,稍后会有的😂
    博哥小时候好厉害:@HenryCheng 楼主啊 我翻了遍你的博客没有找到用黑魔法换全局字体的帖子呢
    HenryCheng:@Easyzhan 可以的
  • 加菲猫爱我:用message forwarding 去实现 one-to-N的delegates也是一个不错的使用例子。
    HenryCheng:@加菲猫爱我 嗯

本文标题:runtime那些事(消息机制)

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