Objct-C 中+load和+initialize

+load

@interfaceLPPerson:NSObject

@end

@implementationLPPerson

+ (void)load {

NSLog(@"LPPerson---+load");

}

@end

@interfaceLPPerson(Test1)

@end

@implementationLPPerson(Test1)

+ (void)load {

NSLog(@"LPPerson (Test1)---+load");

}

@end

@interfaceLPPerson(Test2)

@end

@implementationLPPerson(Test2)

+ (void)load {

NSLog(@"LPPerson (Test2)---+load");

}

@end

intmain(intargc,constchar* argv[]) {

@autoreleasepool{


    }

return0;

}

// 打印結果

LPPerson---+load

LPPerson (Test1)---+load

LPPerson (Test2)---+load
複製代碼

從上面代碼能夠看出:即便咱們在咱們沒有調用LPPerson類、LPPerson分類也會打印。git

打印一下類方法, 這裏咱們要使用這個分類DLIntrospectiongithub

NSLog(@"%@",[[LPPersonclass] classMethods]);

// 打印結果

(

"+ (void)load",

"+ (void)load",

"+ (void)load"

)
複製代碼

說明類的類方法、類分類的類方法都在元類類方法列表中 下面,咱們將結合runtime開源代碼一塊兒來揭開它們的神祕面紗。數組

  • objc runtime的加載入口是一個叫_objc_init的方法,在library加載前由libSystem dyld調用,進行初始化操做(在objc-os.mm文件中)
  • 調用load_images方法(加載鏡像的意思),而後調用call_load_methods()方法。(加載load方法)
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);
        // 加載load方法之間作一些準備(全部類的load方法調用順序)
        prepare_load_methods((const headerType *)mh);
    }

    // 加載load方法
    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);
    }
}
複製代碼
static void schedule_class_load(Class cls)
{
    if (!cls) return;
    assert(cls->isRealized());  // _read_images should realize

    if (cls->data()->flags & RW_LOADED) return;

    // 1.先將父類的load方法添加到loadable_list中
    schedule_class_load(cls->superclass);
    
    // 2.將cls添加到loadable_list最後面(放到最後面就說明最後調用load方法)
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}
複製代碼
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.首先調用類的load方法
        while (loadable_classes_used > 0) {
            call_class_loads();
        }

        // 2. 調用Category的load方法
        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;
}
複製代碼

首先調用類的load方法 咱們查看怎麼調用類的load方法call_class_loads()bash

static void call_class_loads(void)
{
    int i;
    
    // 存放全部加載的類數組,loadable_classes: 類數組內部存放類的位置,從而獲得多個類之間的調用順序
    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方法(load_method:指向類裏面load方法的內存地址)
        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指針,直接調用:因此全部的load方法都會調用
        (*load_method)(cls, SEL_load);
    }
    
    // Destroy the detached list.
    if (classes) free(classes);
}
複製代碼

+initialize

+initialize 方法是在類或它的子類收到第一條消息以前被調用的,這裏所指的消息包括實例方法和類方法的調用。也就是說 +initialize 方法是以懶加載的方式被調用的,若是程序一直沒有給某個類或它的子類發送消息,那麼這個類的 +initialize 方法是永遠不會被調用的app

咱們來看一下runtime源代碼函數

IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
                       bool initialize, bool cache, bool resolver)
{
    ...
        rwlock_unlock_write(&runtimeLock);
    }
    // 是否初始化 而且 這個類沒有被初始化
    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 } ... } 複製代碼

當咱們給某個類發送消息時,runtime 會調用這個函數在類中查找相應方法的實現或進行消息轉發ui

當類沒有初始化,會調用_class_getNonMetaClass方法this

void _class_initialize(Class cls)
{
    ...
    Class supercls;
    BOOL reallyInitialize = NO;

    // Make sure super is done initializing BEFORE beginning to initialize cls.
    // 父類進行遞歸調用,確保先初始化父類
    supercls = cls->superclass;
    if (supercls  &&  !supercls->isInitialized()) {
        _class_initialize(supercls);
    }

    // Try to atomically set CLS_INITIALIZING.
    monitor_enter(&classInitLock);
    if (!cls->isInitialized() && !cls->isInitializing()) {
        cls->setInitializing();
        reallyInitialize = YES;
    }
    monitor_exit(&classInitLock);

    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());
        }
        // runtime 使用了發送消息 objc_msgSend 的方式對 +initialize 方法進行調用
        ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);

        if (PrintInitializing) {
            _objc_inform("INITIALIZE: finished +[%s initialize]",
    ...
}
複製代碼

走的都是發送消息的流程。換言之,若是子類沒有實現 +initialize 方法,那麼繼承自父類的實現會被調用;若是一個類的分類實現了 +initialize 方法,那麼就會先調用分類的+initialize 方法atom

總結 spa

總結.png
相關文章
相關標籤/搜索