一:前言
在iOS 开发中我们经常使用-(instancetype)init 实现实例初始方法。 但是除此之外还有两个初始方法
+(void)load 和 +(void)initialize 。那么这两个类方法 和 实例的初始化方法有啥区别呢?
二: 代码演示
DEMO下载地址 : https://gitee.com/DeLongYang/iOSFundation 下的LoadInitialize 工程。
苹果官方 文档介绍如下:https://developer.apple.com/documentation/objectivec/nsobject
中。
+(void)initialize
The runtime sends initialize
to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
+(void)load
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:
- All initializers in any framework you link to.
- All
+load
methods in your image. - All C++ static initializers and C/C++
__attribute__(constructor)
functions in your image. - All initializers in frameworks that link to you.
In addition:
- A class’s
+load
method is called after all of its superclasses’+load
methods. - 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.
主要从六方面来探讨:
1.0 [super load] 和 [super initalize] 是否需要手动调用 还是 系统自动调用的 子类继承是否会 自动调用父类的这两个方法?
2.0 不论我们是否 import 某个类 load 方法是否会调用
3.0 添加某个分类后 是否影响 load 和 initalize 的调用 时机
4.0 这两个方法 调用的时候 和 -(instancetype)init 的对比
5.0 static 类变量在load 还是 initalize中初始化
6.0 是否可在 这两个方法中使用其他类的方法。
参考博客1:www.jianshu.com/p/9368ce9bb…