分類category、load、initialize的本質和源碼分析

這篇文章介紹分類category、load、initialize的本質,並分析其源碼。

1. 分類 category

隨着需求的演進,類會遇到一些無法處理的情況,應如何擴展已有的類呢?

通常,繼承和組合是不錯的選擇。但 Objective-C 2.0 中,提供的分類category新特性,可以動態的爲已有類添加新行爲。Category 有以下幾個用途:

  • 爲已有的類添加新行爲。此時,無需原來類的源碼,也無需繼承原來的類。例如,爲 Cocoa Touch framework添加分類方法。添加的分類方法會被子類繼承,在運行時和原始方法沒有區別。
  • 把類的實現根據功能劃分到不同文件。
  • 聲明私有方法。

1.1 聲明、實現一個分類

分類的聲明和類的聲明類似,但有以下幾點不同:

  • 分類名稱寫在類名稱後的圓括號內。
  • 不需要說明父類。
  • 必須導入分類擴展的類。

Child類添加一個分類,如下所示:

#import "Child.h"
NS_ASSUME_NONNULL_BEGIN
@interface Child (Test1)
@property (nonatomic, strong) NSString *title;
- (void)test;
@end
NS_ASSUME_NONNULL_END

#import "Child+Test1.h"
@implementation Child (Test1)
- (void)test {
    NSLog(@"%d %s", __LINE__, __PRETTY_FUNCTION__);
}
- (void)run {
    NSLog(@"%d %s", __LINE__, __PRETTY_FUNCTION__);
}
@end

分類文件名稱一般爲:類名稱+分類名稱,即Child+Test1模式。

如果想使用分類爲自己的類添加私有方法,可以把分類的聲明放到類實現文件的@implementation前。

1.2 調用分類方法

Runtime從入門到進階一中,介紹了runtime的消息發送機制:

調用對象方法時,根據實例對象的isa查找到類對象,在類對象的方法列表中查找方法,找到後直接調用;如果找不到,則根據superclass指針,進入父類查找。找到後直接調用;如果找不到,則繼續向父類查找。以此類推,直到找到方法,或拋出doesNotRecognizeSelector:異常。

爲上面的Child類繼續添加Child+Test2分類,ChildChild+Test1Child+Test2都實現了test方法。使用以下代碼調用test方法,看最終調用哪個test方法。

    Child *child = [[Child alloc] init];
    [child test];

執行後控制檯打印如下:

13 -[Child(Test2) test]

即調用了分類的test方法。事實上,類、分類實現了同一方法時,總是優先調用分類的方法。一個類的多個分類實現了同一方法時,後編譯的優先調用,後續會介紹這一現象的本質原因。

類根據 Xcode 中Build Phases > Compile Sources 文件順序進行編譯,自上而下依次編譯:

你可以手動拖動文件,改變其編譯順序。拖動後,再次執行上述代碼,看控制檯輸出是否發生了改變。

1.3 分類的底層結構

分類的方法不是在編譯期合併到原來類中的,而是在運行時合併進去的。

使用clang命令可以將 Objective-C 的代碼轉換爲 C++,方便查看其底層實現,命令如下:

xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc <objc文件名稱.m> -o <輸出文件名稱.cpp>

Child+Test1.m轉換爲Child+Test1.cpp文件命令如下:

xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Child+Test1.m -o Child+Test1.cpp

生成的Child+Test1.cpp文件有三萬四千行,滑到底部可以看到 category 的數據結構:

struct _category_t {
    const char *name;   // 類名
    struct _class_t *cls;
    const struct _method_list_t *instance_methods;  // 分類對象方法列表
    const struct _method_list_t *class_methods; // 分類類方法列表
    const struct _protocol_list_t *protocols;   // 分類協議列表
    const struct _prop_list_t *properties;  // 分類屬性列表
};

繼續向下查找,可以看到對象方法列表如下:

static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[2];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_Child_$_Test1 __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_objc_method),
    2,
    {{(struct objc_selector *)"test", "v16@0:8", (void *)_I_Child_Test1_test},
    {(struct objc_selector *)"run", "v16@0:8", (void *)_I_Child_Test1_run}}
};

它包含了testrun兩個方法。

Child+Test2類添加添加NSCodingNSCoping協議和其他類方法。再次使用clang命令將其轉換爲C++。可以看到其中的協議列表、類方法列表增加了相應的內容。如下所示:

static struct /*_protocol_list_t*/ {
    long protocol_count;  // Note, this is 32/64 bit
    struct _protocol_t *super_protocols[2];
} _OBJC_CATEGORY_PROTOCOLS_$_Child_$_Test2 __attribute__ ((used, section ("__DATA,__objc_const"))) = {  // 協議
    2,
    &_OBJC_PROTOCOL_NSCoding,
    &_OBJC_PROTOCOL_NSCopying
};

1.4 分類category_t結構

這裏使用的是objc4最新源碼objc4-818.2。在源碼中,category結構體如下:

struct category_t {
    const char *name;   // 類名
    classref_t cls;
    WrappedPtr<method_list_t, PtrauthStrip> instanceMethods;    // 實例方法列表
    WrappedPtr<method_list_t, PtrauthStrip> classMethods;   // 類方法列表
    struct protocol_list_t *protocols;  // 協議列表
    struct property_list_t *instanceProperties; // 屬性列表
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties;

    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
    
    protocol_list_t *protocolsForMeta(bool isMeta) {
        if (isMeta) return nullptr;
        else return protocols;
    }
};

通過源碼可以看到,分類中有實例方法列表、類方法列表、協議列表、屬性列表,但沒有成員變量列表。因此,分類中是不能添加成員變量的。分類中添加的屬性並不會自動生成成員變量,只會生成get、set方法的聲明,需要開發者自行實現訪問器方法。

通過源碼看到,category的實例方法、類方法、協議、屬性存放在category_t結構體中。目前,分類裏的信息和類裏的信息是分開存儲的。

那麼是如何合併到原來類中的?

1.5 分類信息合併到類源碼

程序一運行,就會把所有類對象、類對象信息、元類等,加載到內存中。

RunTime 的入口在objc-os.mm文件的_objc_init()方法中:

/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/

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();
    runtime_init();
    exception_init();
#if __OBJC2__
    cache_t::init();
#endif
    _imp_implementationWithBlock_init();

    // image是模塊、鏡像,並非圖片。
    _dyld_objc_notify_register(&map_images, load_images, unmap_image);

#if __OBJC2__
    didCallDyldNotifyRegister = true;
#endif
}

map_images()會調用map_images_nolock()函數,map_images_nolock()會調用_read_images()函數,_read_images()函數如下:

/***********************************************************************
* _read_images
* Perform initial processing of the headers in the linked 
* list beginning with headerList. 
*
* Called by: map_images_nolock
*
* Locking: runtimeLock acquired by map_images
**********************************************************************/
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
    // 省略部分...

    // 分類
    // Discover categories. Only do this after the initial category
    // attachment has been done. For categories present at startup,
    // discovery is deferred until the first load_images call after
    // the call to _dyld_objc_notify_register completes. rdar://problem/53119145
    if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            // 加載分類
            load_categories_nolock(hi);
        }
    }

    ts.log("IMAGE TIMES: discover categories");

    // Category discovery MUST BE Late to avoid potential races
    // when other threads call the new category code before
    // this thread finishes its fixups.

    // +load handled by prepare_load_methods()

    // 省略部分...
    }

#undef EACH_HEADER
}

這裏調用了load_categories_nolock()函數:

static void load_categories_nolock(header_info *hi) {
    bool hasClassProperties = hi->info()->hasCategoryClassProperties();

    size_t count;
    auto processCatlist = [&](category_t * const *catlist) {
        for (unsigned i = 0; i < count; i++) {
            category_t *cat = catlist[I];
            Class cls = remapClass(cat->cls);
            locstamped_category_t lc{cat, hi};

            if (!cls) {
                // Category's target class is missing (probably weak-linked).
                // Ignore the category.
                if (PrintConnecting) {
                    _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
                                 "missing weak-linked target class",
                                 cat->name, cat);
                }
                continue;
            }

            // Process this category.
            if (cls->isStubClass()) {
                // Stub classes are never realized. Stub classes
                // don't know their metaclass until they're
                // initialized, so we have to add categories with
                // class methods or properties to the stub itself.
                // methodizeClass() will find them and add them to
                // the metaclass as appropriate.
                if (cat->instanceMethods ||
                    cat->protocols ||
                    cat->instanceProperties ||
                    cat->classMethods ||
                    cat->protocols ||
                    (hasClassProperties && cat->_classProperties))
                {
                    objc::unattachedCategories.addForClass(lc, cls);
                }
            } else {
                // First, register the category with its target class.
                // Then, rebuild the class's method lists (etc) if
                // the class is realized.
                // 先向類註冊分類,再重建類的方法列表。
                if (cat->instanceMethods ||  cat->protocols
                    ||  cat->instanceProperties)
                {
                    if (cls->isRealized()) {
                        // 附加分類
                        attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls);
                    }
                }

                if (cat->classMethods  ||  cat->protocols
                    ||  (hasClassProperties && cat->_classProperties))
                {
                    if (cls->ISA()->isRealized()) {
                        // 附加分類
                        attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls->ISA());
                    }
                }
            }
        }
    };

    processCatlist(hi->catlist(&count));
    processCatlist(hi->catlist2(&count));
}

其中調用attachCategories()函數,將分類的的實例方法、協議、屬性、類方法合併到類中。attachCategories()函數如下:

// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order, 
// oldest categories first.
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
                 int flags)
{
    if (slowpath(PrintReplacedMethods)) {
        printReplacements(cls, cats_list, cats_count);
    }
    if (slowpath(PrintConnecting)) {
        _objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
                     cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
                     cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
    }

    /*
     * Only a few classes have more than 64 categories during launch.
     * This uses a little stack, and avoids malloc.
     *
     * Categories must be added in the proper order, which is back
     * to front. To do that with the chunking, we iterate cats_list
     * from front to back, build up the local buffers backwards,
     * and call attachLists on the chunks. attachLists prepends the
     * lists, so the final result is in the expected order.
     */
    // 分類從後向前添加。
    constexpr uint32_t ATTACH_BUFSIZ = 64;
    // 方法數組
    method_list_t   *mlists[ATTACH_BUFSIZ];
    // 屬性數組
    property_list_t *proplists[ATTACH_BUFSIZ];
    // 協議數組
    protocol_list_t *protolists[ATTACH_BUFSIZ];

    uint32_t mcount = 0;
    uint32_t propcount = 0;
    uint32_t protocount = 0;
    bool fromBundle = NO;
    bool isMeta = (flags & ATTACH_METACLASS);
    auto rwe = cls->data()->extAllocIfNeeded();

    for (uint32_t i = 0; i < cats_count; i++) {
        // 取出某個分類
        auto& entry = cats_list[I];

        // 取出對象方法或類方法
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            if (mcount == ATTACH_BUFSIZ) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        property_list_t *proplist =
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            if (propcount == ATTACH_BUFSIZ) {
                rwe->properties.attachLists(proplists, propcount);
                propcount = 0;
            }
            proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) {
                rwe->protocols.attachLists(protolists, protocount);
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
    }

    if (mcount > 0) {
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        // 將所有分類的對象方法,附加到類對象的方法列表中。
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }

    // 將所有分類的屬性,附加到類對象的屬性列表中。
    rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);

    // 將所有分類的協議,附加到類對象的協議中。
    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}

上述函數調用了attachLists()函數,attachLists()函數如下:

    /*
     addedLists是二維數組
     [
        [method_t, method_t]
        [method_t, method_t]
     ]
     
     addedCount是分類數量
     */
    void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return;

        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;
            uint32_t newCount = oldCount + addedCount;
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
            newArray->count = newCount;
            array()->count = newCount;

            for (int i = oldCount - 1; i >= 0; I--)
            // array()->lists是原來的方法列表
                newArray->lists[i + addedCount] = array()->lists[I];
            
            // addedLists是所有分類的方法列表,把分類方法列表放到方法列表前面。
            for (unsigned i = 0; i < addedCount; I++)
                newArray->lists[i] = addedLists[I];
            free(array());
            setArray(newArray);
            validate();
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
            validate();
        } 
        else {
            // 1 list -> many lists
            Ptr<List> oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount;
            setArray((array_t *)malloc(array_t::byteSize(newCount)));
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList;
            for (unsigned i = 0; i < addedCount; I++)
                array()->lists[i] = addedLists[I];
            validate();
        }
    }

可以看到,合併時先將原來類中的方法向後移動,再將分類方法放到方法列表前面。因此,進行方法查找時,先找到分類方法,找到後不再查找,這就形成了分類方法會覆蓋類方法的錯覺。

事實上,如果分類和原來類都有同樣方法時,category附加完成後方法列表會有兩個相同的方法,只是分類方法位於列表前面,優先查找到分類方法。

分類的方法列表和類的實例方法一樣,最終放在同一個類對象的方法列表,並不會存放在單獨的方法列表中。類方法、協議、屬性等類似。

2. load方法

多數情況下,開發者無需關心 Objective-C 中的類是如何加載進內存的,這一複雜過程由 runtime 的 linker 處理,並且會在你的代碼開始執行前處理完成。

多數類無需關心類加載過程,但有時可能需要初始化全局表、用戶數據緩存等任務。

Objective-C runtime 提供了+load+initialize兩個方法,用於解決上述問題。

2.1 介紹

如果實現了+load方法,其會在加載類時被調用。+load只會調用一次,並且是在調用main()函數前調用。如果在可加載的 bundle 實現了+load方法,他會在 bundle 加載過程中調用。

因爲+load被調用的時機太早了,可能產生一些很奇怪的問題。例如,在+load方法中使用其他類時,無法確定其他類是否已經加載了;C++ 中的 static initializer 此階段還沒有執行,如果你依賴了其中的方法會導致閃退。但 framework 中的類已經加載完畢,你可以使用 framework 中的類。父類已經加載完成,可以安全使用。

2.2 使用

通過代碼驗證一下+load方法的調用。

創建Person類,繼承自NSObject,創建Person的兩個分類Person+Test1Person+Test2。創建繼承自PersonStudent類,創建Student的兩個分類Student+Test1Student+Test2。所有類、分類都實現+load方法,如下所示:

+ (void)load {
    NSLog(@"%d %s", __LINE__, __PRETTY_FUNCTION__);
}

多次執行後,控制檯總是先打印Person+load方法,後打印Student+load方法,最後根據編譯順序打印分類+load方法。拖動Build Phases > Compile Sources文件順序,可以修改編譯順序。

2.3 源碼分析

RunTime 入口函數_objc_init()load_images()函數開始調用+load方法。

void
load_images(const char *path __unused, const struct mach_header *mh)
{
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
        didInitialAttachCategories = true;
        loadAllCategories();
    }

    // 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
    {
        mutex_locker_t lock2(runtimeLock);
        // 先調用
        prepare_load_methods((const headerType *)mh);
    }

    // Call +load methods (without runtimeLock - re-entrant)
    // 後調用
    call_load_methods();
}

call_load_methods()函數先調用父類的+load,等父類的+load結束後纔會調用分類的+load方法。如下所示:

/***********************************************************************
* 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) {
            // 先調用class的load方法
            call_class_loads();
        }

        // 2. Call category +loads ONCE
        // 後調用分類的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;
}

call_class_loads()函數調用所有掛起類的+load方法。如果有新的類變爲可加載,並不會調用他們的+load方法。找到+load方法函數地址後,直接調用。如下所示:

/***********************************************************************
* 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方法的函數地址
        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_method)(cls, @selector(load));
    }
    
    // Destroy the detached list.
    if (classes) free(classes);
}

調用分類的+load方法與調用類的+load方法類似,也是通過函數指針直接指向函數,拿到函數地址,找到函數直接調用。如下所示:

/***********************************************************************
* 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方法地址
        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方法
            (*load_method)(cls, @selector(load));
            cats[i].cat = nil;
        }
    }

        // 省略...
}

loadable_classloadable_category結構體如下:

struct loadable_class {
    Class cls;  // may be nil
    IMP method; // 函數實現地址,指向類的load方法。
};

struct loadable_category {
    Category cat;  // may be nil
    IMP method; // 函數實現地址,指向分類的load方法
};

Runtime的消息機制需要通過isa指針查找類對象、元類對象,進一步在方法列表中查找方法。+load方法的調用不是通過消息機制進行的,而是直接找到函數指針,拿到函數地址,直接調用函數。因此,類、分類同時實現了+load方法時,都會被調用。但如果使用[Person load]方式調用+load方法,則會使用消息機制進行調用。此時,分類的+load方法會被優先調用。

通過源碼的call_class_loads()call_category_loads()函數,可以看到調用類、分類+load方法時,都是通過for循環loadable_classesloadable_categories數組進行的。因此,知道數組的順序,就可以知道方法調用順序。

load_images()函數在調用call_load_methods()函數前調用了prepare_load_methods()方法。prepare_load_methods()方法會把類、分類添加到相應數組:

void prepare_load_methods(const headerType *mhdr)
{
    size_t count, I;

    runtimeLock.assertLocked();

    classref_t const *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    for (i = 0; i < count; i++) {
        // 將類、未加載的父類添加到loadable_classes數組。
        schedule_class_load(remapClass(classlist[i]));
    }

    category_t * const *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
        if (cls->isSwiftStable()) {
            _objc_fatal("Swift class extensions and categories on Swift "
                        "classes are not allowed to have +load methods");
        }
        realizeClassWithoutSwift(cls, nil);
        ASSERT(cls->ISA()->isRealized());
        // 將分類添加到loadable_categories數組
        add_category_to_loadable_list(cat);
    }
}

schedule_class_load()會遞歸調用,確保先將未加載的父類添加到loadable_classes數組。

/***********************************************************************
* 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
    // 遞歸調用,確保先將父類添加到loadable_classes數組。
    schedule_class_load(cls->getSuperclass());

    // 將類cls添加到loadable_classes數組
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}

如果類實現了+load方法,add_class_to_loadable_list()函數會將其添加到loadable_classes數組,準備加載。

/***********************************************************************
* add_class_to_loadable_list
* Class cls has just become connected. Schedule it for +load if
* it implements a +load method.
**********************************************************************/
// 如果類實現了`+load`方法,add_class_to_loadable_list()函數會將其添加到loadable_classes數組,準備加載。
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()函數將分類+load方法添加到loadable_categories數組:

/***********************************************************************
* 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.
**********************************************************************/
// 將分類添加到loadable_categories數組
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++;
}

2.4 load方法總結

通過上述源碼可以發現,數組的添加順序決定+load方法調用順序。添加順序是:

  1. 先添加父類。
  2. 後添加類。
  3. 最後添加分類。如果有多個分類,先編譯的先添加,可手動設置編譯順序。

3. initialize方法

+initialize方法是懶加載的,加載類時不會調用,首次向類發消息時纔會調用。因此+initialize方法可能不被調用。

將消息發送給類時,runtime先檢查是否調用了+initialize。如果沒有調用,會在發消息之前調用。僞代碼如下:

    id objc_msgSend(id self, SEL _cmd, ...) {
        if(!self->class->initialized)
            [self->class initialize];
        ...send the message...
    }

實際情況可能比上述僞代碼複雜些,例如需考慮線程安全,但整體邏輯沒有變化。每個類的+initialize方法只調用一次,發生在首次向其發送消息時。與+load方法類似,如果父類的+initialize沒有調用過,先調用父類的+initialize,再調用該類的+initialize方法。

+load方法相比,+initialize更爲安全。收到消息後纔會調用+initialize方法,其調用時機取決於消息發送,但肯定會晚於NSApplicationMain()函數的調用。

由於調用+initialize方法是懶加載的方式進行的,其不適合於註冊類。例如,NSValueTransformerNSURLProtocol協議的子類不能使用+initialize方法向父類註冊。因爲,父類註冊完成才能調用子類,而子類想要在父類註冊前添加自身。

+initialize適用於上述類型之外的任務。由於其他類已經加載完成,你可以任意調用其他代碼。由於使用了懶加載,直到使用類時才執行,不會浪費資源。

3.1 使用

爲load部分創建的類添加+initialize方法,此外創建繼承自NSObjectDogCat類,分別實現+initialize方法:

+ (void)initialize {
    NSLog(@"%d %s %@", __LINE__, __PRETTY_FUNCTION__, self);
}

使用以下代碼向類發送消息:

    [Dog alloc];
    [Cat alloc];
    [Person alloc];
    [Student alloc];

執行後控制檯輸出如下:

13 +[Dog initialize] Dog
13 +[Cat initialize] Cat
17 +[Person(Test2) initialize] Person
17 +[Student(Test2) initialize] Student

雖然所有分類、類都實現了+initialize方法,但只調用了分類的方法。因此,可以推測+initialize的調用依賴消息機制,而非+load的找到函數地址直接調用模式。

註釋掉Student類、分類中的+initialize方法,執行後輸出如下:

13 +[Dog initialize] Dog
13 +[Cat initialize] Cat
17 +[Person(Test2) initialize] Person
17 +[Person(Test2) initialize] Student

可以看到Person+Test2+initialize方法調用了兩次,第一次是Person調用,第二次是Student調用。因此,當子類沒有實現+initialize方法時,會查找調用父類方法。與消息機制的查找模式一致。

因此,要避免類的+initialize被多次調用,應使用以下方式編寫+initialize代碼:

+ (void)initialize {
    if (self == [ClassName self]) {
        NSLog(@"%d %s %@", __LINE__, __PRETTY_FUNCTION__, self);
    }
}

如果不添加上述判斷,子類沒有重寫+initialize方法會導致父類的該方法被調用多次。即使你的類沒有子類,也應添加上述判斷,因爲 Apple 的 Key-Value-Observing 會動態創建子類,但不會重寫+initialize方法。因此,添加觀察者後,也會導致+initialize被調用多次。

3.2 源碼分析

class_getInstanceMethod()用來查找實例方法,class_getClassMethod()通過調用class_getInstanceMethod()來查找類方法:

/***********************************************************************
* class_getClassMethod.  Return the class method for the specified
* class and selector.
**********************************************************************/
Method class_getClassMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;

    return class_getInstanceMethod(cls->getMeta(), sel);
}

class_getInstanceMethod()函數用來搜索方法:

/***********************************************************************
* class_getInstanceMethod.  Return the instance method for the
* specified class and selector.
**********************************************************************/
Method class_getInstanceMethod(Class cls, SEL sel)
{
    if (!cls  ||  !sel) return nil;

    // This deliberately avoids +initialize because it historically did so.

    // This implementation is a bit weird because it's the only place that 
    // wants a Method instead of an IMP.

#warning fixme build and search caches
        
    // Search method lists, try method resolver, etc.
    // 搜索方法
    lookUpImpOrForward(nil, sel, cls, LOOKUP_RESOLVER);

#warning fixme build and search caches

    return _class_getMethod(cls, sel);
}

lookUpImpOrForward()函數調用了realizeAndInitializeIfNeeded_locked()函數,realizeAndInitializeIfNeeded_locked()函數調用了realizeAndInitializeIfNeeded_locked()函數,realizeAndInitializeIfNeeded_locked()函數調用了initializeAndLeaveLocked()函數,initializeAndLeaveLocked()函數調用了initializeAndMaybeRelock()函數,initializeAndMaybeRelock()函數調用了initializeNonMetaClass()函數。

initializeNonMetaClass()函數會查看父類是否已經調用過+initialize方法,如果父類沒有調用過,遞歸調用,先讓父類調用+initialize方法。如下所示:

/***********************************************************************
* class_initialize.  Send the '+initialize' message on demand to any
* uninitialized class. Force initialization of superclasses first.
**********************************************************************/
void initializeNonMetaClass(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->getSuperclass();
    if (supercls  &&  !supercls->isInitialized()) {
        // 如果父類沒有調用過 initialize,遞歸調用父類的。
        initializeNonMetaClass(supercls);
    }
    
    // Try to atomically set CLS_INITIALIZING.
    SmallVector<_objc_willInitializeClassCallback, 1> localWillInitializeFuncs;
    {
        monitor_locker_t lock(classInitLock);
        if (!cls->isInitialized() && !cls->isInitializing()) {
            cls->setInitializing();
            reallyInitialize = YES;

            // Grab a copy of the will-initialize funcs with the lock held.
            localWillInitializeFuncs.initFrom(willInitializeFuncs);
        }
    }
    
    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;
        }
        
        for (auto callback : localWillInitializeFuncs)
            callback.f(callback.context, 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: thread %p: calling +[%s initialize]",
                         objc_thread_self(), cls->nameForLogging());
        }

        // Exceptions: A +initialize call that throws an exception 
        // is deemed to be a complete and successful +initialize.
        //
        // Only __OBJC2__ adds these handlers. !__OBJC2__ has a
        // bootstrapping problem of this versus CF's call to
        // objc_exception_set_functions().
#if __OBJC2__
        @try
#endif
        {
            // 調用initialize方法。
            callInitialize(cls);

            if (PrintInitializing) {
                _objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
                             objc_thread_self(), cls->nameForLogging());
            }
        }
#if __OBJC2__
        @catch (...) {
            if (PrintInitializing) {
                _objc_inform("INITIALIZE: thread %p: +[%s initialize] "
                             "threw an exception",
                             objc_thread_self(), cls->nameForLogging());
            }
            @throw;
        }
        // 省略...
}

initializeNonMetaClass()函數調用了callInitialize()函數,callInitialize()函數如下所示:

// 使用消息機制,調用initialize
void callInitialize(Class cls)
{
    ((void(*)(Class, SEL))objc_msgSend)(cls, @selector(initialize));
    asm("");
}

可以看到,callInitialize最終使用objc_msgSend調用了@selector(initialize)。至此,整個調用結束。

Runtime向類發送initialize消息是線程安全的,即首個向類發送消息的線程執行initialize,其他線程會堵塞等待initialize完成。

4. 面試題

4.1 Category的實現原理?

Category編譯之後底層結構是struct category_t,裏面存儲着分類的對象方法、類方法、屬性、協議信息。程序運行的時候,runtime將category的數據合併到類信息中,並且分類信息位於類信息前面。分類方法是後編譯的優先調用。

4.2 Category和Class Extension區別是什麼?

Class Extension 在編譯的時候將數據合併到類信息中。想要添加 Class Extension,必須擁有類的源碼。

Category 在運行時將數據合併到類信息中,可以爲系統 framework、第三方框架等添加 category。

4.3 Category中有+load方法嗎?+load方法是什麼時候調用的?+load方法能繼承嗎?

Category中有+load方法。

程序加載類、分類的時候調用+load方法,在main函數之前。

+load方法可以繼承。調用子類的+load方法之前,會先調用父類的+load方法。一般不手動調用+load方法,而是讓系統去調用。如果手動調用+load方法,就會按照消息發送機制,通過isa指針找到類、元類,之後在方法列表中進行查找。

4.4 load、initialize方法的區別?

  • 調用方式:
    • load根據函數地址直接調用。
    • initialize通過objc_msgSend調用。
  • 調用時機:
    • load是runtime加載類、分類的時候調用,只會調用一次。
    • initialize是類第一次接收消息時調用,每個類只會 initialize 一次,但父類的+initialize方法可能會被調用多次。

4.5 load、initialize調用順序?

  • load
    1. 先調用類的load。
      1. 先編譯的類,優先調用。
      2. 調用子類load前會先調用父類的load。
    2. 後調用分類的load。
      1. 先編譯的分類,優先調用。
  • initialize
    1. 先初始化父類。
    2. 後初始化子類。如果子類沒有實現+initialize方法,最終會調用父類的+initialize方法。

總結

Objective-C 提供了兩種自動配置類的方法,類加載時調用+load方法,對於需要讓代碼運行非常早的情景非常有用。但因爲+load方法調用太早,其他類可能未加載而產生危險。

+initialize方法使用懶加載,首次收到消息時纔會調用,適用場景更廣泛。

Demo名稱:category、load、initialize的本質
源碼地址:https://github.com/pro648/BasicDemos-iOS/tree/master/category、load、initialize的本質

參考資料:

  1. Objective-C Class Loading and Initialization
  2. Category
  3. Customizing Existing Classes
  4. 深入理解Objective-C:Category

歡迎更多指正:https://github.com/pro648/tips

本文地址:https://github.com/pro648/tips/blob/master/sources/分類category、load、initialize的本質和源碼分析.md

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章