NSObject +(void)load 和+(void)initialize 方法的理解

GracKanil發表於2018-07-25

runtime 原始碼,理解 +(void)load+(void)initialize 方法。

零、官方文件

  • initialize Initializes the class before it receives its first message.

  • load Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.

根據文件,+load 方法只要檔案被引用就會被呼叫,所以如果類沒有被引進專案,就不會呼叫 +load+initialize 方法是在類或者子類的第一個方法(拋一個問題,那 runtime 呼叫 +load 方法呢,算第一個方法嗎?)被呼叫之前呼叫,即使類被引用進專案,但沒有被使用, +initialize 也不會被呼叫。兩者都只會被呼叫一次。

一、實驗田

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];,結果如下

# 呼叫了 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 中。

# 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 方法。

# `+(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 方法。

# 根據以上的 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 呼叫的鉤子方法

常見理論知識彙總

  • 呼叫順序:父類 > 子類 > 分類
  • 呼叫時機:Objective-C 執行時初始化時,每當有新的映象library map 到執行時呼叫。
  • 呼叫次數:一次
  • 執行緒安全:load 方法是執行緒安全的,內部使用了鎖,應避免執行緒阻塞在 load 中。
  • 常見場景:load 中實現 Method Swizzle。
  • one more thing:如果一個類本身沒有 load 方法,不管其父類是否實現 load,都不會呼叫,主類和分類都執行。

基於 runtime 原始碼分析

針對 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);
}
複製程式碼

load_images

所以每當有新的 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();
}
複製程式碼

prepare_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

遞迴呼叫 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); 
}
複製程式碼

call_load_methods

當 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_listadd_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_loadscall_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 是在類或者它的子類收到第一條訊息(例項方法、類方法)之前被呼叫的。

常見理論知識彙總

  • 呼叫順序:父類 > 子類(或分類)
  • 呼叫時機:Objective-C 執行時初始化時,每當有新的映象library map 到執行時呼叫。
  • 呼叫次數:多次,如果子類未實現+(void)initialize ,父類+(void)initialize 會被呼叫多次
  • 執行緒安全:在initialize方法收到呼叫時,執行環境基本健全。initialize的執行過程中是能保證執行緒安全的。
  • 常見場景:稍微廣泛,初始化工作,或者單例模式的實現方案。

基於 runtime 原始碼分析

lookUpImpOrForward

當一個類收到訊息時,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 進行初始化,對入參的引數父類遞迴的呼叫 _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("");
}
複製程式碼

Tips

如果子類沒有實現 +(void)initialize,父類會被呼叫多次,只想呼叫父類 initialize 一次呢。

+ (void)initialize {
  if (self == [ClassName self]) {
    
  }
}
# 或者 dispatch_once 了
複製程式碼

推薦文章

相關文章