從
runtime
源碼,理解+(void)load
和+(void)initialize
方法。html
initialize Initializes the class before it receives its first message.git
load Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.github
根據文檔,+load
方法只要文件被引用就會被調用,因此若是類沒有被引進項目,就不會調用 +load
。+initialize
方法是在類或者子類的第一個方法(拋一個問題,那 runtime 調用 +load
方法呢,算第一個方法嗎?)被調用以前調用,即便類被引用進項目,但沒有被使用, +initialize
也不會被調用。二者都只會被調用一次。objective-c
Demo數組
# Father.h 和 Father.m
@interface Father : NSObject
@end
#import "Father.h"
#pragma mark - Father
@implementation Father
+ (void)load {
# [self class];
NSLog(@"%s", __FUNCTION__);
}
+ (void)initialize {
NSLog(@"%s", __FUNCTION__);
}
@end
複製代碼
# Son .h 和 .m
@interface Son : Father
@end
@implementation Son
+ (void)load {
# [self class];
NSLog(@"%s", __FUNCTION__);
}
+ (void)initialize {
NSLog(@"%s", __FUNCTION__);
}
@end
複製代碼
# Category Active of Son .h and .m
@interface Son (Active)
@end
@implementation Son (Active)
+ (void)load {
# [self class];
NSLog(@"%s", __FUNCTION__);
}
+ (void)initialize {
NSLog(@"%s", __FUNCTION__);
}
@end
複製代碼
# Category Stiff of Son .h and .m
@interface Son (Stiff)
@end
@implementation Son (Stiff)
+ (void)load {
# [self class];
NSLog(@"%s", __FUNCTION__);
}
+ (void)initialize {
NSLog(@"%s", __FUNCTION__);
}
@end
複製代碼
結果以下安全
# 父類的方法優先於子類的方法,類中的方法優先於類別中的方法。
2018-02-01 10:59:11.957088+0800 LoadAndInitializePlot[21886:9588221] +[Father load]
2018-02-01 10:59:11.957867+0800 LoadAndInitializePlot[21886:9588221] +[Son load]
2018-02-01 10:59:11.957997+0800 LoadAndInitializePlot[21886:9588221] +[Son(Active) load]
2018-02-01 10:59:11.958132+0800 LoadAndInitializePlot[21886:9588221] +[Son(Stiff) load]
複製代碼
在 Father load 中添加 [self class];
,結果以下bash
# 調用了 Father 中的方法,第一個方法`[self class];`被調用時,在調用方法以前執行 `+initialize` 方法。能夠看出,雖然引用了 Son 類,但沒有調用 Son 的 `+initalize`,同時 runtime 對 `+(void)load` 的調用不視爲調用類的第一個方法,若是是子類 Son 也會調用 `+initialize` 的。
2018-02-01 11:03:38.424049+0800 LoadAndInitializePlot[21961:9595895] +[Father initialize]
2018-02-01 11:03:38.424803+0800 LoadAndInitializePlot[21961:9595895] +[Father load]
2018-02-01 11:03:38.424953+0800 LoadAndInitializePlot[21961:9595895] +[Son load]
2018-02-01 11:03:38.425123+0800 LoadAndInitializePlot[21961:9595895] +[Son(Active) load]
2018-02-01 11:03:38.425418+0800 LoadAndInitializePlot[21961:9595895] +[Son(Stiff) load]
複製代碼
在 Son load 中添加 [self class];
,結果以下兩種(在Build Phases -> Compile Sources 中拖動類別的上下順序,也就是編譯的前後順序)。根據 runtime 對 category 加載過程,一個類的全部類別的方法被取出放在 method_list_t 中,另外,這裏的新生成的 category 的方法會先於 早期生成的 category 的方法,倒序添加的。生成全部 method 的 list 以後,將全部的方法 前序 添加到類的方法數組中。原來的類的方法被 category 的方法覆蓋,但被覆蓋的方法依舊還在裏面。這是由於系統調用方法,根據方法名在 method_list 中查找方法,找到第一個名字匹配的方法以後就不繼續往下找了。每次調用都是 method_list 中最前面的同名方法,其餘的方法仍在 method_list 中。app
# Son (Stiff) 類別在 Son (Active) 後編譯
2018-02-01 11:46:45.558933+0800 LoadAndInitializePlot[22604:9665625] +[Father load]
2018-02-01 11:46:45.559605+0800 LoadAndInitializePlot[22604:9665625] +[Father initialize]
2018-02-01 11:46:45.559735+0800 LoadAndInitializePlot[22604:9665625] +[Son(Stiff) initialize]
2018-02-01 11:46:45.559876+0800 LoadAndInitializePlot[22604:9665625] +[Son load]
2018-02-01 11:46:45.560021+0800 LoadAndInitializePlot[22604:9665625] +[Son(Active) load]
2018-02-01 11:46:45.560125+0800 LoadAndInitializePlot[22604:9665625] +[Son(Stiff) load]
複製代碼
# Son (Active) 類別在 Son (Stiff) 後編譯
2018-02-01 11:50:33.255480+0800 LoadAndInitializePlot[22659:9671829] +[Father load]
2018-02-01 11:50:33.256105+0800 LoadAndInitializePlot[22659:9671829] +[Father initialize]
2018-02-01 11:50:33.256236+0800 LoadAndInitializePlot[22659:9671829] +[Son(Active) initialize]
2018-02-01 11:50:33.256363+0800 LoadAndInitializePlot[22659:9671829] +[Son load]
2018-02-01 11:50:33.256449+0800 LoadAndInitializePlot[22659:9671829] +[Son(Stiff) load]
2018-02-01 11:50:33.256531+0800 LoadAndInitializePlot[22659:9671829] +[Son(Active) load]
複製代碼
在 Son load 中添加 [self class];
,移除 Son 主類和兩個類別中的 +initilize 方法。less
# `+(void)initialize` 自身未定義,會沿用父類的方法。
2018-02-01 11:54:27.282176+0800 LoadAndInitializePlot[22722:9678734] +[Father load]
2018-02-01 11:54:27.282749+0800 LoadAndInitializePlot[22722:9678734] +[Father initialize]
2018-02-01 11:54:27.282843+0800 LoadAndInitializePlot[22722:9678734] +[Father initialize]
2018-02-01 11:54:27.282955+0800 LoadAndInitializePlot[22722:9678734] +[Son load]
2018-02-01 11:54:27.283046+0800 LoadAndInitializePlot[22722:9678734] +[Son(Stiff) load]
2018-02-01 11:54:27.283157+0800 LoadAndInitializePlot[22722:9678734] +[Son(Active) load]
複製代碼
在 Son load 中添加 [self class];
,移除 兩個類別的 +initilize 方法。ide
# 根據以上的 runtime 中的分析可知,`+(void)initialize`會「覆蓋」類中的方法,只執行一個。
2018-02-01 11:56:00.047404+0800 LoadAndInitializePlot[22756:9681679] +[Father load]
2018-02-01 11:56:00.051067+0800 LoadAndInitializePlot[22756:9681679] +[Father initialize]
2018-02-01 11:56:00.051389+0800 LoadAndInitializePlot[22756:9681679] +[Son initialize]
2018-02-01 11:56:00.051745+0800 LoadAndInitializePlot[22756:9681679] +[Son load]
2018-02-01 11:56:00.052070+0800 LoadAndInitializePlot[22756:9681679] +[Son(Stiff) load]
2018-02-01 11:56:00.052350+0800 LoadAndInitializePlot[22756:9681679] +[Son(Active) load]
複製代碼
+(void)load
的理解+load 方法是 Objective-C 中 NSObject 的一個方法,在整個文件剛被加載到運行時,在 main 函數調用以前被 ObjC runtime 調用的鉤子方法。
library
map 到運行時調用。針對 runtime 源碼 objc4-723 ,作一下探討。 xnu 內核爲程序準備好以後,將控制權交個 dyld 負責後續工做,dyld 是 Apple 的動態連接器, the dynamic link editor 的縮寫。此過程內核態切換到用戶態,dyld 在用戶態。
####_objc_init 每當 libSystem 在 library 初始化以前都會調用 _objc_init
方法,dyld 在方法中註冊 load_images 回調。
/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/
# pragma mark - ObjC runtime 初始化 註冊 load_images 回調
void _objc_init(void)
{
static bool initialized = false;
if (initialized) return;
initialized = true;
// fixme defer initialization until an objc-using image is found?
environ_init();
tls_init();
static_init();
lock_init();
exception_init();
_dyld_objc_notify_register(&map_2_images, load_images, unmap_image);
}
複製代碼
因此每當有新的 library 被 map 到 runtime 時,調用 load_images 方法。
/***********************************************************************
* load_images
* Process +load in the given images which are being mapped in by dyld.
*
* Locking: write-locks runtimeLock and loadMethodLock
**********************************************************************/
extern bool hasLoadMethods(const headerType *mhdr);
extern void prepare_load_methods(const headerType *mhdr);
void
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();
}
複製代碼
在主類的父類和自身添加到全局靜態結構體 loadable_list 中以後,添加主類的分類,將分類添加到全局靜態結構體 loadable_categories 中。因此子類優先分類。
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);
}
}
複製代碼
遞歸調用 schedule_class_load ,在將當前類加入全局靜態結構體 loadable_classes 以前,將父類加入其中,待後續加載。保證了父類在子類以前調用 load 方法。
/***********************************************************************
* prepare_load_methods
* Schedule +load for classes in this image, any un-+load-ed
* superclasses in other images, and any categories in this image.
**********************************************************************/
// Recursively schedule +load for cls and any un-+load-ed superclasses.
// cls must already be connected.
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);
}
複製代碼
當 library 加載到運行時,prepare 調用結束,執行 call_load_methods();
/***********************************************************************
* call_load_methods
* Call all pending class and category +load methods.
* Class +load methods are called superclass-first.
* Category +load methods are not called until after the parent class's +load. * * This method must be RE-ENTRANT, because a +load could trigger * more image mapping. In addition, the superclass-first ordering * must be preserved in the face of re-entrant calls. Therefore, * only the OUTERMOST call of this function will do anything, and * that call will handle all loadable classes, even those generated * while it was running. * * The sequence below preserves +load ordering in the face of * image loading during a +load, and make sure that no * +load method is forgotten because it was added during * a +load call. * Sequence: * 1. Repeatedly call class +loads until there aren't any more
* 2. Call category +loads ONCE.
* 3. Run more +loads if:
* (a) there are more classes to load, OR
* (b) there are some potential category +loads that have
* still never been attempted.
* Category +loads are only run once to ensure "parent class first"
* ordering, even if a category +load triggers a new loadable class
* and a new loadable category attached to that class.
*
* Locking: loadMethodLock must be held by the caller
* All other locks must not be held.
**********************************************************************/
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; } 複製代碼
add_class_to_loadable_list
和 add_category_to_loadable_list
方法
// List of classes that need +load called (pending superclass +load)
// This list always has superclasses first because of the way it is constructed
static struct loadable_class *loadable_classes = nil;
static int loadable_classes_used = 0;
static int loadable_classes_allocated = 0;
// List of categories that need +load called (pending parent class +load)
static struct loadable_category *loadable_categories = nil;
static int loadable_categories_used = 0;
static int loadable_categories_allocated = 0;
/***********************************************************************
* add_class_to_loadable_list
* Class cls has just become connected. Schedule it for +load if
* it implements a +load 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++; } /*********************************************************************** * add_category_to_loadable_list * Category cat's parent class exists and the category has been attached
* to its class. Schedule this category for +load after its parent class
* becomes connected and has its own +load method called.
**********************************************************************/
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++; } 複製代碼
call_class_loads
和 call_category_loads
方法
/***********************************************************************
* call_class_loads
* Call all pending class +load methods.
* If new classes become loadable, +load is NOT called for them.
*
* Called only by call_load_methods().
**********************************************************************/
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);
}
/***********************************************************************
* call_category_loads
* Call some pending category +load methods.
* The parent class of the +load-implementing categories has all of
* its categories attached, in case some are lazily waiting for +initalize.
* Don't call +load unless the parent class is connected. * If new categories become loadable, +load is NOT called, and they * are added to the end of the loadable list, and we return TRUE. * Return FALSE if no new categories became loadable. * * Called only by call_load_methods(). **********************************************************************/ 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;
}
複製代碼
+(void)initialize
的理解+(void)initialize
是在類或者它的子類收到第一條消息(實例方法、類方法)以前被調用的。
library
map 到運行時調用。+(void)initialize
,父類+(void)initialize
會被調用屢次當一個類收到消息時,runtime 會經過 IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver)
方法查找方法的實現返回函數指針 IMP,或者進行消息轉發。
/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup.
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known.
* If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use
* must be converted to _objc_msgForward or _objc_msgForward_stret.
* If you don't want forwarding at all, use lookUpImpOrNil() instead. **********************************************************************/ IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver) { ... if (initialize && !cls->isInitialized()) { _class_initialize (_class_getNonMetaClass(cls, inst)); // If sel == initialize, _class_initialize will send +initialize and // then the messenger will send +initialize again after this // procedure finishes. Of course, if this is not being called // from the messenger then it won't happen. 2778172
}
...
}
複製代碼
若是類沒有被初始化,會調用 _class_initialize
進行初始化,對入參的參數父類遞歸的調用 _class_initialize
,這也就是父類優先子類調用的本質。是否是對「Talk is cheap. Show me the code.」深表體會;)
/***********************************************************************
* class_initialize. Send the '+initialize' message on demand to any
* uninitialized class. Force initialization of superclasses first.
**********************************************************************/
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); // Send the +initialize message. // Note that +initialize is sent to the superclass (again) if // this class doesn't implement +initialize. 2157218
if (PrintInitializing) {
_objc_inform("INITIALIZE: calling +[%s initialize]",
cls->nameForLogging());
}
// Exceptions: A +initialize call that throws an exception
// is deemed to be a complete and successful +initialize.
@try {
callInitialize(cls);
if (PrintInitializing) {
_objc_inform("INITIALIZE: finished +[%s initialize]",
cls->nameForLogging());
}
}
@catch (...) {
if (PrintInitializing) {
_objc_inform("INITIALIZE: +[%s initialize] threw an exception",
cls->nameForLogging());
}
@throw;
}
@finally {
// Done initializing.
// If the superclass is also done initializing, then update
// the info bits and notify waiting threads.
// If not, update them later. (This can happen if this +initialize
// was itself triggered from inside a superclass +initialize.)
monitor_locker_t lock(classInitLock);
if (!supercls || supercls->isInitialized()) {
_finishInitializing(cls, supercls);
} else {
_finishInitializingAfter(cls, supercls);
}
}
return;
}
else if (cls->isInitializing()) {
// We couldn't set INITIALIZING because INITIALIZING was already set. // If this thread set it earlier, continue normally. // If some other thread set it, block until initialize is done. // It's ok if INITIALIZING changes to INITIALIZED while we're here, // because we safely check for INITIALIZED inside the lock // before blocking. if (_thisThreadIsInitializingClass(cls)) { return; } else { waitForInitializeToComplete(cls); return; } } else if (cls->isInitialized()) { // Set CLS_INITIALIZING failed because someone else already // initialized the class. Continue normally. // NOTE this check must come AFTER the ISINITIALIZING case. // Otherwise: Another thread is initializing this class. ISINITIALIZED // is false. Skip this clause. Then the other thread finishes // initialization and sets INITIALIZING=no and INITIALIZED=yes. // Skip the ISINITIALIZING clause. Die horribly. return; } else { // We shouldn't be here.
_objc_fatal("thread-safe class init in objc runtime is buggy!");
}
}
複製代碼
callInitialize 中使用 objc_msgSend 方式對 +(void)initialize 進行調用,也就是和普通方法走消息發送的流程,若是子類沒有實現,走父類的方法,若是分類實現,就會對主類進行「覆蓋」,若是多個分類,不肯定調用哪個分類的同名方法,須要看編譯的過程。
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
asm("");
}
複製代碼
若是子類沒有實現 +(void)initialize
,父類會被調用屢次,只想調用父類 initialize 一次呢。
+ (void)initialize {
if (self == [ClassName self]) {
}
}
# 或者 dispatch_once 了
複製代碼