Runtime

作者: 小圆菜陪你财务自由 | 来源:发表于2018-09-26 18:27 被阅读0次
    runtime是什么?

    官网介绍如下:
    The Objective-C language defers as many decisions as it can from compile time and link time to runtime. Whenever possible, it does things dynamically. This means that the language requires not just a compiler, but also a runtime system to execute the compiled code. The runtime system acts as a kind of operating system for the Objective-C language; it’s what makes the language work.
    从介绍中我们大致可以了解到,runtime扮演了一个操作系统的角色,就是有了它OC才有了动态运行时的机制。

    runtime能做什么?

    一句话概括就是:使OC语言能够动态运行(有些废话,不过也是事实),可以在运行时做一系列修改、获取、删除、添加等操作。

    OC方法底层调用过程

    本质就是消息发送机制:objc_msgSend(消息接受对象,方法名称,...)
    demo可见github

    至于objc_msgSend的执行过程大致可能分为三步:

    1. 消息发送
    2. 动态方法解析
    3. 消息转发
    runtime是通过c/c++/汇编来实现的,详细可以通过它的源码得知,源码可以从githum上面下载得到
    
    消息发送的过程
    1. 判断消息的接收者(receiver)是否为空,如果是空,直接返回。如果不为空,执行第二步。
    2. 通过isa指针和一个野码的“与(and)”操作(汇编实现),找到对应的类。然后从类的缓存中去找IMP,如果找不到则去方法列表中去找,如果还找不到,就到父类的缓存和方法列表去找,一直到根类为止,如果没有找到方法,则执行一次动态方法解析,如果找到了则执行第三步。
    3. 如果在缓存中找到,则返回IMP,如果在方法列表中找到,则首先把IMP添加到缓存中,然后返回IMP.
      以上是消息发送的执行过程。
    动态方法解析

    如果我们调用的方法没有实现,那么会调用resolveInstanceMethod或resolveClassMethod方法。

    1. resolveClassMethod:通过字面意思可以明白,这个方法是在类方法没有实现的情况下调用。
    2. resolveInstanceMethod:当然是在实例方法没有实现的情况下调用。
    3. 在上面的方法中我们可以动态去添加方法的实现,实现细节可查看demo的runtime_02
    消息转发

    动态方法解析如果没有找到方法的实现,那么就会进行消息的转发:
    汲及到的方法有:

    1. forwardingTargetForSelector
    2. methodSignatureForSelector //方法注册
    3. forwardInvocation //存储注册信息
      说的不够准确,大家可以网上查下具体描述。
      消息转发的实现,实现细节可查看demo的runtime_03
    runtime常用api示例代码:

    可查看demo的runtime04

    相关文章

      网友评论

          本文标题:Runtime

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