细说OC中的load和initialize方法

时间:2023-10-09 14:36:20

OC中有两个特殊的类方法,分别是loadinitialize。本文总结一下这两个方法的区别于联系、使用场景和注意事项。Demo可以在我的Github上找到——load和initialize,如果觉得有帮助还望点个关注以示支持,总结在文章末尾。

先来看看NSObject Class Reference里对这两个方法说明:

+(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.

  initialize方法不一定会执行。只有当一个类第一次被发送消息的时候会执行,注意是第一次。什么叫发送消息呢,就是执行类的一些方法的时候。也就是说这个方法是懒加载,没有用到这个类就不会调用,可以节省系统资源。还有一点截然相反,却更符合我们预期的就是,initialize方法会覆盖。也就是说如果子类实现了initialize方法,就不会执行父类的了,直接执行子类本身的。如果分类实现了initialize方法,也不会再执行主类的。所以initialize方法的执行覆盖顺序是 分类 -> 子类 ->类。且只会有一个initialize方法被执行。

调用规则

load方法类似的是,在initialize方法内部也会调用父类的方法,而且不需要我们显示的写出来。与load方法不同之处在于,即使子类没有实现initialize方法,也会调用父类的方法,这会导致一个很严重的问题:

// In Parent.m
+ (void)initialize {
NSLog(@"Initialize Parent, caller Class %@", [self class]);
} // In Child.m
// 注释掉initialize方法 // In main.m
Child *child = [Child new];

运行后发现父类的initialize方法竟然调用了两次:

-- ::56.056 load[:] Initialize Parent, caller Class Parent
-- ::57.179 load[:] Initialize Parent, caller Class Child

这是因为在创建子类对象时,首先要创建父类对象,所以会调用一次父类的initialize方法,然后创建子类时,尽管自己没有实现initialize方法,但还是会调用到父类的方法。

虽然initialize方法对一个类而言只会调用一次,但这里由于出现了两个类,所以调用两次符合规则,但不符合我们的需求。正确使用initialize方法的姿势如下:

// In Parent.m
+ (void)initialize {
if (self == [Parent class]) {
NSLog(@"Initialize Parent, caller Class %@", [self class]);
}
}

加上判断后,就不会因为子类而调用到自己的initialize方法了。

使用场景

initialize方法主要用来对一些不方便在编译期初始化的对象进行赋值。比如NSMutableArray这种类型的实例化依赖于runtime的消息发送,所以显然无法在编译器初始化:

// In Parent.m
static int someNumber = ; // int类型可以在编译期赋值
static NSMutableArray *someObjects; + (void)initialize {
if (self == [Parent class]) {
// 不方便编译期复制的对象在这里赋值
someObjects = [[NSMutableArray alloc] init];
}
}

+(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.

 顾名思义,load方法在这个文件被程序装载时调用。只要是在Compile Sources中出现的文件总是会被装载,这与这个类是否被用到无关,因此load方法总是在main函数之前调用。

调用规则

 如果一个类实现了load方法,在调用这个方法前会首先调用父类的load方法。而且这个过程是自动完成的,并不需要我们手动实现:

// In Parent.m
+ (void)load {
NSLog(@"Load Class Parent");
} // In Child.m,继承自Parent
+ (void)load {
NSLog(@"Load Class Child");
} // In Child+load.m,Child类的分类
+ (void)load {
NSLog(@"Load Class Child+load");
}
/*
2017-04-05 19:14:14.328 load[11739:419339] Load Class Parent
2017-04-05 19:14:14.329 load[11739:419339] Load Class Child
2017-04-05 19:14:14.330 load[11739:419339] Load Class Child+load
*/

如果一个类没有实现load方法,那么就不会调用它父类的load方法,这一点与正常的类继承和方法调用不一样,需要额外注意一下。

执行顺序

load方法调用时,系统处于脆弱状态,如果调用别的类的方法,且该方法依赖于那个类的load方法进行初始化设置,那么必须确保那个类的load方法已经调用了,比如demo中的这段代码,打印出的字符串就为null

// In Child.m
+ (void)load {
NSLog(@"Load Class Child"); Other *other = [Other new];
[other originalFunc]; // 如果不先调用other的load,下面这行代码就无效,打印出null
[Other printName];
}
首先,如果所有类都继承NSObject没有继承关系,load方法的调用顺序是

细说OC中的load和initialize方法

从上到下依次执行loda方法然后再执行main方法。如果类之间有继承关系,先调用父类的load方法。load方法是一定会在runtime中被调用的,只要类被添加到runtime中了,就会调用load方法,所以我们可以自己实现laod方法来在这个时候执行一些行为。而且有意思的一点是,load方法不会覆盖。也就是说,如果子类实现了load方法,那么会先调用父类的load方法,然后又去执行子类的load方法。同样的,如果分类实现了load方法,也会先执行主类的load方法,然后又会去执行分类的load方法。所以父类的load会执行很多次,这一点需要注意。而且执行顺序是 类 -> 子类 ->分类。而不同类之间的顺序不一定。

注意事项:
虽然在这种简单情况下我们可以辨别出各个类的load方法调用的顺序,但永远不要依赖这个顺序完成你的代码逻辑。一方面,这在后期的开发中极容易导致错误,另一方面,你实际上并不需要这么做。

使用场景:

由于调用load方法时的环境很不安全,我们应该尽量减少load方法的逻辑。另一个原因是load方法是线程安全的,它内部使用了锁,所以我们应该避免线程阻塞在load方法中。

一个常见的使用场景是在load方法中实现Method Swizzle:
// In Other.m
+ (void)load {
Method originalFunc = class_getInstanceMethod([self class], @selector(originalFunc));
Method swizzledFunc = class_getInstanceMethod([self class], @selector(swizzledFunc)); method_exchangeImplementations(originalFunc, swizzledFunc);
}
Child类的load方法中,由于还没调用Otherload方法,所以输出结果是"Original Output",而在main函数中,输出结果自然就变成了"Swizzled Output"。
提示:一般来说,除了Method Swizzle,别的逻辑都不应该放在load方法中实现。

小结:

Apple的文档很清楚地说明了initialize和load的区别在于:load是只要类所在文件被引用就会被调用,而initialize是在类或者其子类的第一个方法被调用前调用。所以如果类没有被引用进项目,就不会有load调用;但即使类文件被引用进来,但是没有使用,那么initialize也不会被调用。

它们的相同点在于:方法只会被调用一次。(其实这是相对runtime来说的,后边会做进一步解释)。

文档也明确阐述了方法调用的顺序:父类(Superclass)的方法优先于子类(Subclass)的方法,类中的方法优先于类别(Category)中的方法。

不过还有很多地方是文章中没有解释详细的。所以再来看一些示例代码来明确其中应该注意的细节。

总结 

  1. loadinitialize方法都会在实例化对象之前调用,以main函数为分水岭,前者在main函数之前调用,后者在之后调用。这两个方法会被自动调用,不能手动调用它们。
  2. loadinitialize方法都不用显示的调用父类的方法而是自动调用,即使子类没有initialize方法也会调用父类的方法,而load方法则不会调用父类。
  3. load方法通常用来进行Method Swizzle,initialize方法一般用于初始化全局变量或静态变量。
  4. loadinitialize方法内部使用了锁,因此它们是线程安全的。实现时要尽可能保持简单,避免阻塞线程,不要再使用锁。

  温馨提示:亲手自己用代码尝试下代码,运行几次会更加明白。Demo可以在我的Github上找到——load和initialize(如有问题大家一起商讨)