load方法和initialize方法类似点
1. 都只会调用一次2. 父类在子类之前加载
复制代码
不同点在于:
1. 加载时间不同,load方法在main()函数前进行调用,initialize在第一次调用类的所属方法时在调用<可能永远不调用>。2. load方法不会被Category覆盖。
复制代码
initialize源码
//向对象发送消息时,lookUpImpOrForward函数判断对象是否初始化,没有初始化则先初始化在调用类的方法
IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bo ol resolver);
//第一次调用类
if (initialize && !cls->isInitialized()) {_class_initialize (_class_getNonMetaClass(cls, inst));}// 第一次调用类的方法,初始化对象
void _class_initialize(Class cls) {Class supercls;bool reallyInitialize = NO;// 递归初始化父类supercls = cls->superclass;if (supercls && !supercls->isInitialized()) {_class_initialize(supercls);}{monitor_locker_t lock(classInitLock);if (!cls->isInitialized() && !cls->isInitializing()) {cls->setInitializing();reallyInitialize = YES;}}if (reallyInitialize) { _setThisThreadIsInitializingClass(cls);if (MultithreadedForkChild) { performForkChildInitialize(cls, supercls);return;}@try {// 通过objc_msgSend函数调用initialize方法callInitialize(cls);}@catch (...) { @throw;}@finally {// 执行initialize方法后,进行系统的initialize过程lockAndFinishInitializing(cls, supercls);}return;}else if (cls->isInitializing()) {if (_thisThreadIsInitializingClass(cls)) {return;} else if (!MultithreadedForkChild) {waitForInitializeToComplete(cls);return; } else {_setThisThreadIsInitializingClass(cls);performForkChildInitialize(cls, supercls);}}
}
复制代码