之前在看項目組件化方案的時候蟀拷,看到蘑菇街的組件化方案中有在load
方法中注冊vc的方法囤采。
所以想要完整了解一下load
方法的具體細節(jié)免胃,另外發(fā)現(xiàn)initialize
方法基本上和load
是成對出現(xiàn)的狰闪,所以順便就一起看一下辛润。
initialize
官方文檔
Initializes the class before it receives its first message.
(在類收到第一條消息之前初始化它。)
官方文檔中對initialize方法的描述就一種懶加載的形式崎场,在類第一次收到消息的之前初始化。
源碼
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
return lookUpImpOrForward(cls, sel, obj,
YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
//如果initialize==Yes,說明需要初始化,并且該類沒有進行過初始化,然后調(diào)用_class_initialize進行初始化
if (initialize && !cls->isInitialized()) {
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
}
}
void _class_initialize(Class cls)
{
assert(!cls->isMetaClass());
Class supercls;
bool reallyInitialize = NO;
// Make sure super is done initializing BEFORE beginning to initialize cls.
// See note about deadlock above.
//在初始化之前先確保父類進行了初始化操作,如果沒有就先初始化父類
supercls = cls->superclass;
if (supercls && !supercls->isInitialized()) {
_class_initialize(supercls);
}
// Try to atomically set CLS_INITIALIZING.
{
monitor_locker_t lock(classInitLock);
if (!cls->isInitialized() && !cls->isInitializing()) {
cls->setInitializing();
reallyInitialize = YES;
}
}
if (reallyInitialize) {
// We successfully set the CLS_INITIALIZING bit. Initialize the class.
// Record that we're initializing this class so we can message it.
_setThisThreadIsInitializingClass(cls);
if (MultithreadedForkChild) {
// LOL JK we don't really call +initialize methods after fork().
performForkChildInitialize(cls, supercls);
return;
}
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: calling +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
//調(diào)用初始化發(fā)送,
callInitialize(cls);
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
return;
}
else if (cls->isInitializing()) {
if (_thisThreadIsInitializingClass(cls)) {
return;
} else if (!MultithreadedForkChild) {
waitForInitializeToComplete(cls);
return;
} else {
_setThisThreadIsInitializingClass(cls);
performForkChildInitialize(cls, supercls);
}
}
else if (cls->isInitialized()) {
return;
}
else {
// We shouldn't be here.
_objc_fatal("thread-safe class init in objc runtime is buggy!");
}
}
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
asm("");
}
可以看到遂蛀,調(diào)用時會先去查看父類是否存在谭跨,并且父類是否有初始化過,如果滿足條件之后李滴,就會遞歸去調(diào)用
if (supercls && !supercls->isInitialized()) {
_class_initialize(supercls);
}
最后可以看到調(diào)用了一個方法callInitialize(cls)
仔細看這個方法螃宙,其實內(nèi)部就是一個objc_msgSend
。
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
asm("");
}
方法實現(xiàn)
接下來我們通過一些代碼來看一下initialize
的執(zhí)行順序所坯。
首先我們創(chuàng)建一個類ZZRInitizial
谆扎,然后重寫一下他的initialize
方法。
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZZRInitizial : NSObject
@end
NS_ASSUME_NONNULL_END
--------------------------------------------------------------
#import "ZZRInitizial.h"
@implementation ZZRInitizial
+ (void)initialize
{
NSLog(@"%s",__FUNCTION__);
}
@end
然后運行一下芹助,發(fā)現(xiàn)堂湖,什么都沒有打印,不過因為之前看過文檔和源碼状土,initialize是使用懶加載調(diào)用的无蜂,所以當我們沒有用到它的時候沒有打印也很正常。接下來我們試一下初始化一個實例蒙谓。
[ZZRInitizial new];
可以看到現(xiàn)在就打印出來了
2019-05-05 13:58:26.566212+0800 initializeDemo[86317:3926410] +[ZZRInitizial initialize]
接下來我們定義一個繼承了ZZRInitizial
的子類ZZRInitizialSubClass
斥季,然后再調(diào)用子類的初始化實例。
[ZZRInitizialSubClass new];
然后可以看到打印出的方法
2019-05-05 14:02:42.331628+0800 initializeDemo[86412:3934965] +[ZZRInitizial initialize]
2019-05-05 14:02:42.331745+0800 initializeDemo[86412:3934965] +[ZZRInitizialSubClass initialize]
接下來我們再創(chuàng)建一個ZZRInitizial
的Category,然后初始化一個實例
2019-05-05 14:22:32.726589+0800 initializeDemo[86608:3962561] +[ZZRInitizial(myCategory) initialize]
我們會發(fā)現(xiàn)調(diào)用的是Category中的方法酣倾,而沒有調(diào)用原本類中的方法了舵揭。
總結
所以我們可以看到,initialize在類或者其子類的第一個方法被調(diào)用之前調(diào)用躁锡,并且使用懶加載的調(diào)用方式午绳,即沒有使用就不會調(diào)用。
并且因為是有系統(tǒng)調(diào)用稚铣,所以不需要再調(diào)用[super initialize]
箱叁。
調(diào)用順序上,會先調(diào)用父類的initialize
惕医,然后再調(diào)用原有類的initialize
耕漱,如果有Category,并且Category中重寫了initialize方法抬伺,則會調(diào)用Category中的initialize
螟够。
load
官方文檔
Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.
(當類或者類別加入runtime時,實現(xiàn)該方法峡钓,可以在類加載的時候做一些類特有的操作)
以上是官方文檔中對load
方法的描述妓笙,也就是說當類被加入runtime,也就是被引用的時候能岩,就會實現(xiàn)該方法寞宫。
另外,在每一個類拉鹃、分類在程序運行的過程中除了手動調(diào)用之外辈赋,只會調(diào)用一次。
源碼
load_images(const char *path __unused, const struct mach_header *mh)
{
// Return without taking locks if there are no +load methods here.
if (!hasLoadMethods((const headerType *)mh)) return;
recursive_mutex_locker_t lock(loadMethodLock);
// Discover load methods
{
rwlock_writer_t lock2(runtimeLock);
prepare_load_methods((const headerType *)mh);
}
// Call +load methods (without runtimeLock - re-entrant)
call_load_methods();
}
void prepare_load_methods(const headerType *mhdr)
{
size_t count, i;
runtimeLock.assertWriting();
classref_t *classlist =
_getObjc2NonlazyClassList(mhdr, &count);
for (i = 0; i < count; i++) {
schedule_class_load(remapClass(classlist[i]));
}
category_t **categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
for (i = 0; i < count; i++) {
category_t *cat = categorylist[i];
Class cls = remapClass(cat->cls);
if (!cls) continue; // category for ignored weak-linked class
realizeClass(cls);
assert(cls->ISA()->isRealized());
add_category_to_loadable_list(cat);
}
}
//遞歸查找父類,父類優(yōu)先添加到集合中
static void schedule_class_load(Class cls)
{
if (!cls) return;
assert(cls->isRealized()); // _read_images should realize
if (cls->data()->flags & RW_LOADED) return;
// Ensure superclass-first ordering
schedule_class_load(cls->superclass);
add_class_to_loadable_list(cls);
cls->setInfo(RW_LOADED);
}
//把類和類的load方法添加到loadable_classes數(shù)組中,數(shù)組中每一個元素都是一個結構體,結構體中包含類和load方法的IMP
static struct loadable_class *loadable_classes = nil;
struct loadable_class {
Class cls; // may be nil
IMP method;
};
void add_class_to_loadable_list(Class cls)
{
IMP method;
loadMethodLock.assertLocked();
method = cls->getLoadMethod();
if (!method) return; // Don't bother if cls has no +load method
if (PrintLoading) {
_objc_inform("LOAD: class '%s' scheduled for +load",
cls->nameForLogging());
}
if (loadable_classes_used == loadable_classes_allocated) {
loadable_classes_allocated = loadable_classes_allocated*2 + 16;
loadable_classes = (struct loadable_class *)
realloc(loadable_classes,
loadable_classes_allocated *
sizeof(struct loadable_class));
}
loadable_classes[loadable_classes_used].cls = cls;
loadable_classes[loadable_classes_used].method = method;
loadable_classes_used++;
}
static struct loadable_category *loadable_categories = nil;
struct loadable_category {
Category cat; // may be nil
IMP method;
};
//處理分類
void add_category_to_loadable_list(Category cat)
{
IMP method;
loadMethodLock.assertLocked();
method = _category_getLoadMethod(cat);
// Don't bother if cat has no +load method
if (!method) return;
if (PrintLoading) {
_objc_inform("LOAD: category '%s(%s)' scheduled for +load",
_category_getClassName(cat), _category_getName(cat));
}
if (loadable_categories_used == loadable_categories_allocated) {
loadable_categories_allocated = loadable_categories_allocated*2 + 16;
loadable_categories = (struct loadable_category *)
realloc(loadable_categories,
loadable_categories_allocated *
sizeof(struct loadable_category));
}
loadable_categories[loadable_categories_used].cat = cat;
loadable_categories[loadable_categories_used].method = method;
loadable_categories_used++;
}
從上邊這段代碼的函數(shù)名就可以看出來膏燕,主要是準備load方法钥屈。
這段代碼處理了類的load方法,遞歸并獲取父類的坝辫,把類和類的load方法的IMP存儲到struct loadable_class
結構體中篷就,并把結構體添加到了loadable_classes
數(shù)組中。
另外處理分類load方法近忙,把分類和分類的load方法的IMP存儲到loadable_category
結構體中竭业,并把結構體添加到了loadable_categories
數(shù)組中。
然后接下來是重頭戲call_load_methods()
void call_load_methods(void)
{
static bool loading = NO;
bool more_categories;
loadMethodLock.assertLocked();
// Re-entrant calls do nothing; the outermost call will finish the job.
if (loading) return;
loading = YES;
void *pool = objc_autoreleasePoolPush();
do {
// 1. Repeatedly call class +loads until there aren't any more
while (loadable_classes_used > 0) {
call_class_loads();
}
// 2. Call category +loads ONCE
more_categories = call_category_loads();
// 3. Run more +loads if there are classes OR more untried categories
} while (loadable_classes_used > 0 || more_categories);
objc_autoreleasePoolPop(pool);
loading = NO;
}
static void call_class_loads(void)
{
int i;
// Detach current loadable list.
struct loadable_class *classes = loadable_classes;
int used = loadable_classes_used;
loadable_classes = nil;
loadable_classes_allocated = 0;
loadable_classes_used = 0;
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
Class cls = classes[i].cls;
load_method_t load_method = (load_method_t)classes[i].method;
if (!cls) continue;
if (PrintLoading) {
_objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
}
(*load_method)(cls, SEL_load);
}
// Destroy the detached list.
if (classes) free(classes);
}
static bool call_category_loads(void)
{
int i, shift;
bool new_categories_added = NO;
// Detach current loadable list.
struct loadable_category *cats = loadable_categories;
int used = loadable_categories_used;
int allocated = loadable_categories_allocated;
loadable_categories = nil;
loadable_categories_allocated = 0;
loadable_categories_used = 0;
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
Category cat = cats[i].cat;
load_method_t load_method = (load_method_t)cats[i].method;
Class cls;
if (!cat) continue;
cls = _category_getClass(cat);
if (cls && cls->isLoadable()) {
if (PrintLoading) {
_objc_inform("LOAD: +[%s(%s) load]\n",
cls->nameForLogging(),
_category_getName(cat));
}
(*load_method)(cls, SEL_load);
cats[i].cat = nil;
}
}
// Compact detached list (order-preserving)
shift = 0;
for (i = 0; i < used; i++) {
if (cats[i].cat) {
cats[i-shift] = cats[i];
} else {
shift++;
}
}
used -= shift;
// Copy any new +load candidates from the new list to the detached list.
new_categories_added = (loadable_categories_used > 0);
for (i = 0; i < loadable_categories_used; i++) {
if (used == allocated) {
allocated = allocated*2 + 16;
cats = (struct loadable_category *)
realloc(cats, allocated *
sizeof(struct loadable_category));
}
cats[used++] = loadable_categories[i];
}
// Destroy the new list.
if (loadable_categories) free(loadable_categories);
// Reattach the (now augmented) detached list.
// But if there's nothing left to load, destroy the list.
if (used) {
loadable_categories = cats;
loadable_categories_used = used;
loadable_categories_allocated = allocated;
} else {
if (cats) free(cats);
loadable_categories = nil;
loadable_categories_used = 0;
loadable_categories_allocated = 0;
}
if (PrintLoading) {
if (loadable_categories_used != 0) {
_objc_inform("LOAD: %d categories still waiting for +load\n",
loadable_categories_used);
}
}
return new_categories_added;
}
這段代碼主要調(diào)用了類的load方法及舍,優(yōu)先調(diào)用父類的load方法永品,然后調(diào)用分類的load方法。
調(diào)用父類的load方法主要是通過(*load_method)(cls, SEL_load);
方法直接調(diào)用指針击纬。
但是手動調(diào)用和自動調(diào)用的區(qū)別就是手動調(diào)用的時候是通過objc_msgSend
而不是指針鼎姐。
方法實現(xiàn)
同樣的,我們新建一個類ZZRLoad
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZZRLoad : NSObject
@end
NS_ASSUME_NONNULL_END
----------------------------------------
#import "ZZRLoad.h"
@implementation ZZRLoad
+ (void)load
{
NSLog(@"%s",__FUNCTION__);
}
@end
然后運行代碼,我們就會發(fā)現(xiàn)炕桨,ZZRLoad
的load
方法就已經(jīng)執(zhí)行了饭尝,而且是在最前邊執(zhí)行的。
2019-05-05 15:34:56.613609+0800 initializeDemo[87221:4058674] +[ZZRLoad load]
接下來基于ZZRLoad
創(chuàng)建一個子類ZZRLoadSubClass
献宫,然后運行會發(fā)現(xiàn):
2019-05-05 15:38:25.778688+0800 initializeDemo[87271:4065322] +[ZZRLoad load]
2019-05-05 15:38:25.779203+0800 initializeDemo[87271:4065322] +[ZZRLoadSubClass load]
兩個方法都執(zhí)行了load钥平。
然后基于ZZRLoad
創(chuàng)建一個分類,運行后會發(fā)現(xiàn):
2019-05-05 15:39:26.135793+0800 initializeDemo[87297:4067390] +[ZZRLoad load]
2019-05-05 15:39:26.136449+0800 initializeDemo[87297:4067390] +[ZZRLoadSubClass load]
2019-05-05 15:39:26.136542+0800 initializeDemo[87297:4067390] +[ZZRLoad(myCategory) load]
三個也都執(zhí)行了姊途。
總結
Load方法會在runtime加載類涉瘾、分類的時候調(diào)用,每個類捷兰、分類的load方法在程序運行的過程中只會調(diào)用一次(你手動調(diào)用的不算數(shù))立叛。由于load函數(shù)是系統(tǒng)自動加載的,因此不需要調(diào)用父類的load函數(shù)贡茅,否則父類的load函數(shù)會多次執(zhí)行秘蛇。
區(qū)別
系統(tǒng)中為了保障線程安全,在load方法內(nèi)部使用了鎖顶考,所以我們在使用的時候盡量需要在load方法中添加太多邏輯赁还,防止線程阻塞。
對弈initialize方法中主要用來對一些不方便在編譯期初始化的對象進行賦值驹沿。
參考資料
load - NSObject | Apple Developer Documentation
initialize - NSObject | Apple Developer Documentation
iOS類方法load和initialize詳解 - 掘金
【OC底層】Category艘策、+load方法、+initialize方法原理 - 這酸爽渊季! - 博客園
iOS - + initialize 與 +load - 簡書
通過源碼查看load和initialize - 簡書