意識到load方法是因為最近學習Method Swilzzing時發現與其它的系統方法不同。 當時創建了一個UIViewController的catagory並重寫了load方法。
在這篇文章中指出:
+ load 作為 Objective-C 中的一個方法,與其它方法有很大的不同。只是一個在整個文件被加載到運行時,在 main 函數調用之前被 ObjC 運行時調用的鈎子方法。其中關鍵字有這么幾個:
-
文件剛加載
-
main 函數之前
-
鈎子方法
針對提問進行整理學習
Q1:load 方法是如何被調用的?
A1:當 Objective-C 運行時初始化的時候,會通過 dyld_register_image_state_change_handler 在每次有新的鏡像加入運行時的時候,進行回調。執行 load_images 將所有包含 load 方法的文件加入列表 loadable_classes ,然后從這個列表中找到對應的 load 方法的實現,調用 load 方法。
Q2:load 方法會有為我們所知的這種調用順序?
規則一:父類先於子類調用
規則二:類先於分類調用
A2:分析 schedule_class_load 和 call_load_methods 可得。
// 在系統內核做好程序准備工作之后,交由 dyld(是the dynamic link editor 的縮寫,它是蘋果的動態鏈接器) 負責余下的工作。
// 1、首先在整個運行時初始化時 _objc_init 注冊的回調 dyld_register_image_state_change_handler(dyld_image_state_dependents_initialized, 0/*not batch*/, &load_images);
// 2、每當有新的鏡像加載到 runtime 時,都會執行 load_images 方法進行回調,並傳入最新鏡像的信息列表 infoList const char * load_images(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info infoList[]) { bool found; found = false; for (uint32_t i = 0; i < infoCount; i++) { if (hasLoadMethods((const headerType *)infoList[i].imageLoadAddress)) { // 3、如果在掃描鏡像的過程中發現了 + load 符號 found = true; break; } }
if (!found) return nil; recursive_mutex_locker_t lock(loadMethodLock); { rwlock_writer_t lock2(runtimeLock);
// 4、會進入 load_images_nolock 來查找 load 方法
found = load_images_nolock(state, infoCount, infoList); } if (found) {
// 7、在將鏡像加載到運行時、對 load 方法的准備就緒之后,執行 call_load_methods 開始調用 load 方法 call_load_methods(); } return nil; }
// 4、調用 load_image_nolock bool load_images_nolock(enum dyld_image_states state,uint32_t infoCount, const struct dyld_image_info infoList[] { bool found = NO; uint32_t i; i = infoCount; while (i--) { const headerType *mhdr = (headerType*)infoList[i].imageLoadAddress; if (!hasLoadMethods(mhdr)) continue;
// 5、調用 prepare_load_methods 對 load 方法的調用進行准備 prepare_load_methods(mhdr); found = YES; } return found; } // 5、調用 prepare_load_methods(將需要調用 load 方法的類添加到一個列表中) void prepare_load_methods(const headerType *mhdr) { size_t count, i; runtimeLock.assertWriting();
/* 通過 _getObjc2NonlazyClassList 獲取所有的類的列表 */ classref_t *classlist = _getObjc2NonlazyClassList(mhdr, &count); for (i = 0; i < count; i++) {
// 6、調用 schedule_class_load 遞歸地安排當前類和沒有調用 load 的父類進入列表
/* 通過 remapClass 獲取類對應的指針 */
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);
}
}
// 6、調用 schedule_class_load (紅色代碼保證了父類在子類前面調用 load 方法) static void schedule_class_load(Class cls) { if (!cls) return; assert(cls->isRealized()); if (cls->data()->flags & RW_LOADED) return;
/* 先把父類加入待加載的列表 */ schedule_class_load(cls->superclass);
/* 再執行 add_class_to_loadabel_list 將當前類也加入進去 */ add_class_to_loadable_list(cls); ---------------------------------------》得出規則一 cls->setInfo(RW_LOADED); }
// 其中 add_class_to_loadable_list 添加到待加載的類的列表 void add_class_to_loadable_list(Class cls) { IMP method; loadMethodLock.assertLocked(); method = cls->getLoadMethod(); if (!method) return; 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++; } // 其中 add_category_to_loadable_list 添加到待加載的分類的列表 void add_category_to_loadable_list(Category cat) { IMP method; loadMethodLock.assertLocked(); method = _category_getLoadMethod(cat); if (!method) return; 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++; }
// 7、調用 call_load_methods void call_load_methods(void) { ... do { while (loadable_classes_used > 0) { call_class_loads(); } more_categories = call_category_loads(); --------------------------------》得出規則二 } while (loadable_classes_used > 0 || more_categories); ... }
// 其中call_class_loads 會從一個待加載的類列表 loadable_classes 中尋找對應的類,然后找到 @selector(load) 的實現並執行。 static void call_class_loads(void) { int i; struct loadable_class *classes = loadable_classes; int used = loadable_classes_used; loadable_classes = nil; loadable_classes_allocated = 0; loadable_classes_used = 0; 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; (*load_method)(cls, SEL_load); // 真正調用 +[XXObject load] 方法 } if (classes) free(classes); }
補充:
1)什么是鏡像?
2)由上得出
load_images -> load_images_nolock -> prepare_load_methods -> schedule_class_load -> add_class_to_loadable_list
的調用過程。ObjC 對於加載的管理主要使用了兩個列表,分別是 loadable_classes 和 loadable_categories。其中的add_class_to_loadable_list就是將未加載的類添加到 loadable_classes 數組中,add_category_to_loadable_list實現幾乎相同
3)相比於類 load 方法的調用,分類中 load 方法的調用就有些復雜了
static bool call_category_loads(void) { int i, shift; bool new_categories_added = NO; // 1. 獲取當前可以加載的分類列表 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; 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()) { // 2. 如果當前類是可加載的 `cls && cls->isLoadable()` 就會調用分類的 load 方法 (*load_method)(cls, SEL_load); cats[i].cat = nil; } } // 3. 將所有加載過的分類移除 `loadable_categories` 列表 shift = 0; for (i = 0; i < used; i++) { if (cats[i].cat) { cats[i-shift] = cats[i]; } else { shift++; } } used -= shift; // 4. 為 `loadable_categories` 重新分配內存,並重新設置它的值 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]; } if (loadable_categories) free(loadable_categories); 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; } return new_categories_added; }
