美文网首页
iOS + (void)load 运行流程解析

iOS + (void)load 运行流程解析

作者: 中秋梧桐语 | 来源:发表于2019-10-24 13:51 被阅读0次

+ (void)load方法是在什么时候执行了?

首先我们看官方定义,

Discussion
The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.
The order of initialization is as follows:
1.All initializers in any framework you link to.
2.All +load methods in your image.(这个image指的就是二进制可执行文件)
3.All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.
4.All initializers in frameworks that link to you.
In addition:
1.A class’s +load method is called after all of its superclasses’ +load methods.
2.A category +load method is called after the class’s own +load method.
In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.

大致意思就是只要工程里动态加载或静态引用了这个类,那么load方法就会被执行,他并不需要你显示的去创建一个类后才会执行,同时只执行一次。

运行流程

  1. load方法是加载所有的superclass后才会加载该类的load方法,最后加载分类的load方法。
    大致加载顺序就是 FatherClass-> SonClass -> SonClass+category。
  2. 在工程里加载的顺序是先于 main函数的执行的。也就是说其执行顺序为
    FatherClass-> SonClass -> SonClass+category -> main -> AppDelegate。

实际应用

从上面的运行流程中可知,+(void)load方法是在main函数之前执行,并且只调用一次。而main函数又是整个应用的入口。那么这里使用load方法时,要注意点地方就很多了。

1. 在load方法里不要做耗时操作

因为执行在main函数之前,当执行完所有load方法之后才会启动应用,在load方法中进行耗时操作必然会影响程序的启动时间。

2. 不要进行初始化操作

因为在main函数之前自动调用,load方法调用的时候使用者根本就不能确定自己要使用的对象是否已经加载进来了,所以千万不能在这里初始化对象。

3. 常用的场景就是在load方法中通过runtime实现黑魔法

Method Swizzing是发生在运行时的,主要用于在运行时将两个Method进行交换,我们可以将Method Swizzling代码写到任何地方,当在load方法中实现方法交换,则对整个工程的实现都会起作用。

+ (void)load {
    Method originalMethod = class_getInstanceMethod([self class], @selector(originalMethod));
    Method swizzledMethod = class_getInstanceMethod([self class], @selector(swizzledMethod));
    method_exchangeImplementations(originalMethod, swizzledMethod);
}

此文章只当知识点的记录,参考了其他网友的知识点,在此不一一列出。

相关文章

网友评论

      本文标题:iOS + (void)load 运行流程解析

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