分類(lèi)category徐鹤、load垃环、initialize的本質(zhì)和源碼分析

這篇文章介紹分類(lèi)category、load返敬、initialize的本質(zhì)遂庄,并分析其源碼。

1. 分類(lèi) category

隨著需求的演進(jìn)劲赠,類(lèi)會(huì)遇到一些無(wú)法處理的情況涛目,應(yīng)如何擴(kuò)展已有的類(lèi)呢?

通常凛澎,繼承和組合是不錯(cuò)的選擇霹肝。但 Objective-C 2.0 中,提供的分類(lèi)category新特性塑煎,可以動(dòng)態(tài)的為已有類(lèi)添加新行為沫换。Category 有以下幾個(gè)用途:

  • 為已有的類(lèi)添加新行為。此時(shí)最铁,無(wú)需原來(lái)類(lèi)的源碼讯赏,也無(wú)需繼承原來(lái)的類(lèi)垮兑。例如,為 Cocoa Touch framework添加分類(lèi)方法漱挎。添加的分類(lèi)方法會(huì)被子類(lèi)繼承系枪,在運(yùn)行時(shí)和原始方法沒(méi)有區(qū)別。
  • 把類(lèi)的實(shí)現(xiàn)根據(jù)功能劃分到不同文件磕谅。
  • 聲明私有方法私爷。

1.1 聲明、實(shí)現(xiàn)一個(gè)分類(lèi)

分類(lèi)的聲明和類(lèi)的聲明類(lèi)似怜庸,但有以下幾點(diǎn)不同:

  • 分類(lèi)名稱(chēng)寫(xiě)在類(lèi)名稱(chēng)后的圓括號(hào)內(nèi)当犯。
  • 不需要說(shuō)明父類(lèi)。
  • 必須導(dǎo)入分類(lèi)擴(kuò)展的類(lèi)割疾。

Child類(lèi)添加一個(gè)分類(lèi),如下所示:

#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

分類(lèi)文件名稱(chēng)一般為:類(lèi)名稱(chēng)+分類(lèi)名稱(chēng)嘉栓,即Child+Test1模式宏榕。

如果想使用分類(lèi)為自己的類(lèi)添加私有方法,可以把分類(lèi)的聲明放到類(lèi)實(shí)現(xiàn)文件的@implementation前侵佃。

1.2 調(diào)用分類(lèi)方法

Runtime從入門(mén)到進(jìn)階一中麻昼,介紹了runtime的消息發(fā)送機(jī)制:

調(diào)用對(duì)象方法時(shí),根據(jù)實(shí)例對(duì)象的isa查找到類(lèi)對(duì)象馋辈,在類(lèi)對(duì)象的方法列表中查找方法抚芦,找到后直接調(diào)用;如果找不到迈螟,則根據(jù)superclass指針叉抡,進(jìn)入父類(lèi)查找。找到后直接調(diào)用答毫;如果找不到褥民,則繼續(xù)向父類(lèi)查找。以此類(lèi)推洗搂,直到找到方法消返,或拋出doesNotRecognizeSelector:異常。

為上面的Child類(lèi)繼續(xù)添加Child+Test2分類(lèi)耘拇,Child撵颊、Child+Test1Child+Test2都實(shí)現(xiàn)了test方法惫叛。使用以下代碼調(diào)用test方法倡勇,看最終調(diào)用哪個(gè)test方法。

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

執(zhí)行后控制臺(tái)打印如下:

13 -[Child(Test2) test]

即調(diào)用了分類(lèi)的test方法挣棕。事實(shí)上译隘,類(lèi)亲桥、分類(lèi)實(shí)現(xiàn)了同一方法時(shí),總是優(yōu)先調(diào)用分類(lèi)的方法固耘。一個(gè)類(lèi)的多個(gè)分類(lèi)實(shí)現(xiàn)了同一方法時(shí)题篷,后編譯的優(yōu)先調(diào)用,后續(xù)會(huì)介紹這一現(xiàn)象的本質(zhì)原因厅目。

類(lèi)根據(jù) Xcode 中Build Phases > Compile Sources 文件順序進(jìn)行編譯番枚,自上而下依次編譯:

CategoryCompileSources.png

你可以手動(dòng)拖動(dòng)文件,改變其編譯順序损敷。拖動(dòng)后葫笼,再次執(zhí)行上述代碼,看控制臺(tái)輸出是否發(fā)生了改變拗馒。

1.3 分類(lèi)的底層結(jié)構(gòu)

分類(lèi)的方法不是在編譯期合并到原來(lái)類(lèi)中的路星,而是在運(yùn)行時(shí)合并進(jìn)去的。

使用clang命令可以將 Objective-C 的代碼轉(zhuǎn)換為 C++诱桂,方便查看其底層實(shí)現(xiàn)洋丐,命令如下:

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

Child+Test1.m轉(zhuǎn)換為Child+Test1.cpp文件命令如下:

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

生成的Child+Test1.cpp文件有三萬(wàn)四千行,滑到底部可以看到 category 的數(shù)據(jù)結(jié)構(gòu):

struct _category_t {
    const char *name;   // 類(lèi)名
    struct _class_t *cls;
    const struct _method_list_t *instance_methods;  // 分類(lèi)對(duì)象方法列表
    const struct _method_list_t *class_methods; // 分類(lèi)類(lèi)方法列表
    const struct _protocol_list_t *protocols;   // 分類(lèi)協(xié)議列表
    const struct _prop_list_t *properties;  // 分類(lèi)屬性列表
};

繼續(xù)向下查找挥等,可以看到對(duì)象方法列表如下:

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兩個(gè)方法友绝。

Child+Test2類(lèi)添加添加NSCodingNSCoping協(xié)議和其他類(lèi)方法肝劲。再次使用clang命令將其轉(zhuǎn)換為C++迁客。可以看到其中的協(xié)議列表辞槐、類(lèi)方法列表增加了相應(yīng)的內(nèi)容掷漱。如下所示:

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"))) = {  // 協(xié)議
    2,
    &_OBJC_PROTOCOL_NSCoding,
    &_OBJC_PROTOCOL_NSCopying
};

1.4 分類(lèi)category_t結(jié)構(gòu)

這里使用的是objc4最新源碼objc4-818.2。在源碼中催蝗,category結(jié)構(gòu)體如下:

struct category_t {
    const char *name;   // 類(lèi)名
    classref_t cls;
    WrappedPtr<method_list_t, PtrauthStrip> instanceMethods;    // 實(shí)例方法列表
    WrappedPtr<method_list_t, PtrauthStrip> classMethods;   // 類(lèi)方法列表
    struct protocol_list_t *protocols;  // 協(xié)議列表
    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;
    }
};

通過(guò)源碼可以看到切威,分類(lèi)中有實(shí)例方法列表、類(lèi)方法列表丙号、協(xié)議列表先朦、屬性列表,但沒(méi)有成員變量列表犬缨。因此喳魏,分類(lèi)中是不能添加成員變量的。分類(lèi)中添加的屬性并不會(huì)自動(dòng)生成成員變量怀薛,只會(huì)生成get刺彩、set方法的聲明,需要開(kāi)發(fā)者自行實(shí)現(xiàn)訪(fǎng)問(wèn)器方法。

通過(guò)源碼看到创倔,category的實(shí)例方法嗡害、類(lèi)方法、協(xié)議畦攘、屬性存放在category_t結(jié)構(gòu)體中霸妹。目前,分類(lèi)里的信息和類(lèi)里的信息是分開(kāi)存儲(chǔ)的知押。

那么是如何合并到原來(lái)類(lèi)中的叹螟?

1.5 分類(lèi)信息合并到類(lèi)源碼

程序一運(yùn)行,就會(huì)把所有類(lèi)對(duì)象台盯、類(lèi)對(duì)象信息罢绽、元類(lèi)等,加載到內(nèi)存中静盅。

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()會(huì)調(diào)用map_images_nolock()函數(shù)棚壁,map_images_nolock()會(huì)調(diào)用_read_images()函數(shù),_read_images()函數(shù)如下:

/***********************************************************************
* _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)
{
    // 省略部分...

    // 分類(lèi)
    // 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) {
            // 加載分類(lèi)
            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
}

這里調(diào)用了load_categories_nolock()函數(shù):

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.
                // 先向類(lèi)注冊(cè)分類(lèi)栈虚,再重建類(lèi)的方法列表。
                if (cat->instanceMethods ||  cat->protocols
                    ||  cat->instanceProperties)
                {
                    if (cls->isRealized()) {
                        // 附加分類(lèi)
                        attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                    } else {
                        objc::unattachedCategories.addForClass(lc, cls);
                    }
                }

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

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

其中調(diào)用attachCategories()函數(shù)史隆,將分類(lèi)的的實(shí)例方法魂务、協(xié)議、屬性泌射、類(lèi)方法合并到類(lèi)中粘姜。attachCategories()函數(shù)如下:

// 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.
     */
    // 分類(lèi)從后向前添加。
    constexpr uint32_t ATTACH_BUFSIZ = 64;
    // 方法數(shù)組
    method_list_t   *mlists[ATTACH_BUFSIZ];
    // 屬性數(shù)組
    property_list_t *proplists[ATTACH_BUFSIZ];
    // 協(xié)議數(shù)組
    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++) {
        // 取出某個(gè)分類(lèi)
        auto& entry = cats_list[I];

        // 取出對(duì)象方法或類(lè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__);
        // 將所有分類(lèi)的對(duì)象方法熔酷,附加到類(lèi)對(duì)象的方法列表中孤紧。
        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();
            });
        }
    }

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

    // 將所有分類(lèi)的協(xié)議号显,附加到類(lèi)對(duì)象的協(xié)議中。
    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}

上述函數(shù)調(diào)用了attachLists()函數(shù)躺酒,attachLists()函數(shù)如下:

    /*
     addedLists是二維數(shù)組
     [
        [method_t, method_t]
        [method_t, method_t]
     ]
     
     addedCount是分類(lèi)數(shù)量
     */
    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是原來(lái)的方法列表
                newArray->lists[i + addedCount] = array()->lists[I];
            
            // addedLists是所有分類(lèi)的方法列表押蚤,把分類(lèi)方法列表放到方法列表前面。
            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();
        }
    }

可以看到羹应,合并時(shí)先將原來(lái)類(lèi)中的方法向后移動(dòng)揽碘,再將分類(lèi)方法放到方法列表前面。因此,進(jìn)行方法查找時(shí)雳刺,先找到分類(lèi)方法劫灶,找到后不再查找,這就形成了分類(lèi)方法會(huì)覆蓋類(lèi)方法的錯(cuò)覺(jué)掖桦。

事實(shí)上本昏,如果分類(lèi)和原來(lái)類(lèi)都有同樣方法時(shí),category附加完成后方法列表會(huì)有兩個(gè)相同的方法滞详,只是分類(lèi)方法位于列表前面凛俱,優(yōu)先查找到分類(lèi)方法。

分類(lèi)的方法列表和類(lèi)的實(shí)例方法一樣料饥,最終放在同一個(gè)類(lèi)對(duì)象的方法列表蒲犬,并不會(huì)存放在單獨(dú)的方法列表中。類(lèi)方法岸啡、協(xié)議原叮、屬性等類(lèi)似。

2. load方法

多數(shù)情況下巡蘸,開(kāi)發(fā)者無(wú)需關(guān)心 Objective-C 中的類(lèi)是如何加載進(jìn)內(nèi)存的奋隶,這一復(fù)雜過(guò)程由 runtime 的 linker 處理,并且會(huì)在你的代碼開(kāi)始執(zhí)行前處理完成悦荒。

多數(shù)類(lèi)無(wú)需關(guān)心類(lèi)加載過(guò)程唯欣,但有時(shí)可能需要初始化全局表、用戶(hù)數(shù)據(jù)緩存等任務(wù)搬味。

Objective-C runtime 提供了+load境氢、+initialize兩個(gè)方法,用于解決上述問(wèn)題碰纬。

2.1 介紹

如果實(shí)現(xiàn)了+load方法萍聊,其會(huì)在加載類(lèi)時(shí)被調(diào)用。+load只會(huì)調(diào)用一次悦析,并且是在調(diào)用main()函數(shù)前調(diào)用寿桨。如果在可加載的 bundle 實(shí)現(xiàn)了+load方法,他會(huì)在 bundle 加載過(guò)程中調(diào)用强戴。

因?yàn)?code>+load被調(diào)用的時(shí)機(jī)太早了亭螟,可能產(chǎn)生一些很奇怪的問(wèn)題。例如酌泰,在+load方法中使用其他類(lèi)時(shí)媒佣,無(wú)法確定其他類(lèi)是否已經(jīng)加載了;C++ 中的 static initializer 此階段還沒(méi)有執(zhí)行陵刹,如果你依賴(lài)了其中的方法會(huì)導(dǎo)致閃退默伍。但 framework 中的類(lèi)已經(jīng)加載完畢欢嘿,你可以使用 framework 中的類(lèi)。父類(lèi)已經(jīng)加載完成也糊,可以安全使用炼蹦。

2.2 使用

通過(guò)代碼驗(yàn)證一下+load方法的調(diào)用。

創(chuàng)建Person類(lèi)狸剃,繼承自NSObject掐隐,創(chuàng)建Person的兩個(gè)分類(lèi)Person+Test1Person+Test2钞馁。創(chuàng)建繼承自PersonStudent類(lèi)虑省,創(chuàng)建Student的兩個(gè)分類(lèi)Student+Test1Student+Test2僧凰。所有類(lèi)探颈、分類(lèi)都實(shí)現(xiàn)+load方法,如下所示:

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

多次執(zhí)行后训措,控制臺(tái)總是先打印Person+load方法伪节,后打印Student+load方法,最后根據(jù)編譯順序打印分類(lèi)+load方法绩鸣。拖動(dòng)Build Phases > Compile Sources文件順序怀大,可以修改編譯順序。

2.3 源碼分析

RunTime 入口函數(shù)_objc_init()load_images()函數(shù)開(kāi)始調(diào)用+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);
        // 先調(diào)用
        prepare_load_methods((const headerType *)mh);
    }

    // Call +load methods (without runtimeLock - re-entrant)
    // 后調(diào)用
    call_load_methods();
}

call_load_methods()函數(shù)先調(diào)用父類(lèi)的+load化借,等父類(lèi)的+load結(jié)束后才會(huì)調(diào)用分類(lèi)的+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) {
            // 先調(diào)用class的load方法
            call_class_loads();
        }

        // 2. Call category +loads ONCE
        // 后調(diào)用分類(lèi)的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()函數(shù)調(diào)用所有掛起類(lèi)的+load方法捡多。如果有新的類(lèi)變?yōu)榭杉虞d屏鳍,并不會(huì)調(diào)用他們的+load方法。找到+load方法函數(shù)地址后局服,直接調(diào)用。如下所示:

/***********************************************************************
* 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方法的函數(shù)地址
        load_method_t load_method = (load_method_t)classes[i].method;
        if (!cls) continue; 

        if (PrintLoading) {
            _objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
        }
        // 直接調(diào)用load方法
        (*load_method)(cls, @selector(load));
    }
    
    // Destroy the detached list.
    if (classes) free(classes);
}

調(diào)用分類(lèi)的+load方法與調(diào)用類(lèi)的+load方法類(lèi)似驳遵,也是通過(guò)函數(shù)指針直接指向函數(shù)淫奔,拿到函數(shù)地址,找到函數(shù)直接調(diào)用堤结。如下所示:

/***********************************************************************
* 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;
        // 獲取分類(lèi)的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));
            }
            // 調(diào)用分類(lèi)的load方法
            (*load_method)(cls, @selector(load));
            cats[i].cat = nil;
        }
    }

        // 省略...
}

loadable_classloadable_category結(jié)構(gòu)體如下:

struct loadable_class {
    Class cls;  // may be nil
    IMP method; // 函數(shù)實(shí)現(xiàn)地址唆迁,指向類(lèi)的load方法。
};

struct loadable_category {
    Category cat;  // may be nil
    IMP method; // 函數(shù)實(shí)現(xiàn)地址竞穷,指向分類(lèi)的load方法
};

Runtime的消息機(jī)制需要通過(guò)isa指針查找類(lèi)對(duì)象唐责、元類(lèi)對(duì)象,進(jìn)一步在方法列表中查找方法瘾带。+load方法的調(diào)用不是通過(guò)消息機(jī)制進(jìn)行的鼠哥,而是直接找到函數(shù)指針,拿到函數(shù)地址,直接調(diào)用函數(shù)朴恳。因此抄罕,類(lèi)、分類(lèi)同時(shí)實(shí)現(xiàn)了+load方法時(shí)于颖,都會(huì)被調(diào)用呆贿。但如果使用[Person load]方式調(diào)用+load方法,則會(huì)使用消息機(jī)制進(jìn)行調(diào)用森渐。此時(shí)做入,分類(lèi)的+load方法會(huì)被優(yōu)先調(diào)用。

通過(guò)源碼的call_class_loads()同衣、call_category_loads()函數(shù)竟块,可以看到調(diào)用類(lèi)、分類(lèi)+load方法時(shí)乳怎,都是通過(guò)for循環(huán)loadable_classes彩郊、loadable_categories數(shù)組進(jìn)行的。因此蚪缀,知道數(shù)組的順序但狭,就可以知道方法調(diào)用順序碘饼。

load_images()函數(shù)在調(diào)用call_load_methods()函數(shù)前調(diào)用了prepare_load_methods()方法。prepare_load_methods()方法會(huì)把類(lèi)、分類(lèi)添加到相應(yīng)數(shù)組:

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++) {
        // 將類(lèi)苦囱、未加載的父類(lèi)添加到loadable_classes數(shù)組。
        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());
        // 將分類(lèi)添加到loadable_categories數(shù)組
        add_category_to_loadable_list(cat);
    }
}

schedule_class_load()會(huì)遞歸調(diào)用荤懂,確保先將未加載的父類(lèi)添加到loadable_classes數(shù)組吃靠。

/***********************************************************************
* 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
    // 遞歸調(diào)用,確保先將父類(lèi)添加到loadable_classes數(shù)組渊抄。
    schedule_class_load(cls->getSuperclass());

    // 將類(lèi)cls添加到loadable_classes數(shù)組
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}

如果類(lèi)實(shí)現(xiàn)了+load方法尝胆,add_class_to_loadable_list()函數(shù)會(huì)將其添加到loadable_classes數(shù)組,準(zhǔn)備加載护桦。

/***********************************************************************
* add_class_to_loadable_list
* Class cls has just become connected. Schedule it for +load if
* it implements a +load method.
**********************************************************************/
// 如果類(lèi)實(shí)現(xiàn)了`+load`方法含衔,add_class_to_loadable_list()函數(shù)會(huì)將其添加到loadable_classes數(shù)組,準(zhǔn)備加載二庵。
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()函數(shù)將分類(lèi)+load方法添加到loadable_categories數(shù)組:

/***********************************************************************
* 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.
**********************************************************************/
// 將分類(lèi)添加到loadable_categories數(shù)組
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方法總結(jié)

通過(guò)上述源碼可以發(fā)現(xiàn)贪染,數(shù)組的添加順序決定+load方法調(diào)用順序。添加順序是:

  1. 先添加父類(lèi)催享。
  2. 后添加類(lèi)杭隙。
  3. 最后添加分類(lèi)。如果有多個(gè)分類(lèi)因妙,先編譯的先添加痰憎,可手動(dòng)設(shè)置編譯順序票髓。

3. initialize方法

+initialize方法是懶加載的,加載類(lèi)時(shí)不會(huì)調(diào)用信殊,首次向類(lèi)發(fā)消息時(shí)才會(huì)調(diào)用炬称。因此+initialize方法可能不被調(diào)用。

將消息發(fā)送給類(lèi)時(shí)涡拘,runtime先檢查是否調(diào)用了+initialize玲躯。如果沒(méi)有調(diào)用,會(huì)在發(fā)消息之前調(diào)用鳄乏。偽代碼如下:

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

實(shí)際情況可能比上述偽代碼復(fù)雜些跷车,例如需考慮線(xiàn)程安全,但整體邏輯沒(méi)有變化橱野。每個(gè)類(lèi)的+initialize方法只調(diào)用一次朽缴,發(fā)生在首次向其發(fā)送消息時(shí)。與+load方法類(lèi)似水援,如果父類(lèi)的+initialize沒(méi)有調(diào)用過(guò)密强,先調(diào)用父類(lèi)的+initialize,再調(diào)用該類(lèi)的+initialize方法蜗元。

+load方法相比或渤,+initialize更為安全。收到消息后才會(huì)調(diào)用+initialize方法奕扣,其調(diào)用時(shí)機(jī)取決于消息發(fā)送薪鹦,但肯定會(huì)晚于NSApplicationMain()函數(shù)的調(diào)用。

由于調(diào)用+initialize方法是懶加載的方式進(jìn)行的惯豆,其不適合于注冊(cè)類(lèi)池磁。例如,NSValueTransformer楷兽、NSURLProtocol協(xié)議的子類(lèi)不能使用+initialize方法向父類(lèi)注冊(cè)地熄。因?yàn)椋割?lèi)注冊(cè)完成才能調(diào)用子類(lèi)芯杀,而子類(lèi)想要在父類(lèi)注冊(cè)前添加自身离斩。

+initialize適用于上述類(lèi)型之外的任務(wù)。由于其他類(lèi)已經(jīng)加載完成瘪匿,你可以任意調(diào)用其他代碼。由于使用了懶加載寻馏,直到使用類(lèi)時(shí)才執(zhí)行棋弥,不會(huì)浪費(fèi)資源。

3.1 使用

為load部分創(chuàng)建的類(lèi)添加+initialize方法诚欠,此外創(chuàng)建繼承自NSObjectDog顽染、Cat類(lèi)漾岳,分別實(shí)現(xiàn)+initialize方法:

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

使用以下代碼向類(lèi)發(fā)送消息:

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

執(zhí)行后控制臺(tái)輸出如下:

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

雖然所有分類(lèi)、類(lèi)都實(shí)現(xiàn)了+initialize方法粉寞,但只調(diào)用了分類(lèi)的方法尼荆。因此,可以推測(cè)+initialize的調(diào)用依賴(lài)消息機(jī)制唧垦,而非+load的找到函數(shù)地址直接調(diào)用模式捅儒。

注釋掉Student類(lèi)、分類(lèi)中的+initialize方法振亮,執(zhí)行后輸出如下:

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

可以看到Person+Test2+initialize方法調(diào)用了兩次巧还,第一次是Person調(diào)用,第二次是Student調(diào)用坊秸。因此麸祷,當(dāng)子類(lèi)沒(méi)有實(shí)現(xiàn)+initialize方法時(shí),會(huì)查找調(diào)用父類(lèi)方法褒搔。與消息機(jī)制的查找模式一致阶牍。

因此,要避免類(lèi)的+initialize被多次調(diào)用星瘾,應(yīng)使用以下方式編寫(xiě)+initialize代碼:

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

如果不添加上述判斷走孽,子類(lèi)沒(méi)有重寫(xiě)+initialize方法會(huì)導(dǎo)致父類(lèi)的該方法被調(diào)用多次。即使你的類(lèi)沒(méi)有子類(lèi)死相,也應(yīng)添加上述判斷融求,因?yàn)?Apple 的 Key-Value-Observing 會(huì)動(dòng)態(tài)創(chuàng)建子類(lèi),但不會(huì)重寫(xiě)+initialize方法算撮。因此生宛,添加觀察者后,也會(huì)導(dǎo)致+initialize被調(diào)用多次肮柜。

3.2 源碼分析

class_getInstanceMethod()用來(lái)查找實(shí)例方法陷舅,class_getClassMethod()通過(guò)調(diào)用class_getInstanceMethod()來(lái)查找類(lèi)方法:

/***********************************************************************
* 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()函數(shù)用來(lái)搜索方法:

/***********************************************************************
* 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()函數(shù)調(diào)用了realizeAndInitializeIfNeeded_locked()函數(shù),realizeAndInitializeIfNeeded_locked()函數(shù)調(diào)用了realizeAndInitializeIfNeeded_locked()函數(shù)审洞,realizeAndInitializeIfNeeded_locked()函數(shù)調(diào)用了initializeAndLeaveLocked()函數(shù)莱睁,initializeAndLeaveLocked()函數(shù)調(diào)用了initializeAndMaybeRelock()函數(shù),initializeAndMaybeRelock()函數(shù)調(diào)用了initializeNonMetaClass()函數(shù)芒澜。

initializeNonMetaClass()函數(shù)會(huì)查看父類(lèi)是否已經(jīng)調(diào)用過(guò)+initialize方法仰剿,如果父類(lèi)沒(méi)有調(diào)用過(guò),遞歸調(diào)用痴晦,先讓父類(lèi)調(diào)用+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()) {
        // 如果父類(lèi)沒(méi)有調(diào)用過(guò) initialize,遞歸調(diào)用父類(lèi)的誊酌。
        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
        {
            // 調(diào)用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()函數(shù)調(diào)用了callInitialize()函數(shù)露乏,callInitialize()函數(shù)如下所示:

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

可以看到涂邀,callInitialize最終使用objc_msgSend調(diào)用了@selector(initialize)瘟仿。至此,整個(gè)調(diào)用結(jié)束比勉。

Runtime向類(lèi)發(fā)送initialize消息是線(xiàn)程安全的劳较,即首個(gè)向類(lèi)發(fā)送消息的線(xiàn)程執(zhí)行initialize,其他線(xiàn)程會(huì)堵塞等待initialize完成敷搪。

4. 面試題

4.1 Category的實(shí)現(xiàn)原理兴想?

Category編譯之后底層結(jié)構(gòu)是struct category_t,里面存儲(chǔ)著分類(lèi)的對(duì)象方法赡勘、類(lèi)方法嫂便、屬性、協(xié)議信息闸与。程序運(yùn)行的時(shí)候毙替,runtime將category的數(shù)據(jù)合并到類(lèi)信息中,并且分類(lèi)信息位于類(lèi)信息前面践樱。分類(lèi)方法是后編譯的優(yōu)先調(diào)用厂画。

4.2 Category和Class Extension區(qū)別是什么?

Class Extension 在編譯的時(shí)候?qū)?shù)據(jù)合并到類(lèi)信息中拷邢。想要添加 Class Extension袱院,必須擁有類(lèi)的源碼。

Category 在運(yùn)行時(shí)將數(shù)據(jù)合并到類(lèi)信息中瞭稼,可以為系統(tǒng) framework忽洛、第三方框架等添加 category。

4.3 Category中有+load方法嗎环肘?+load方法是什么時(shí)候調(diào)用的欲虚?+load方法能繼承嗎?

Category中有+load方法悔雹。

程序加載類(lèi)复哆、分類(lèi)的時(shí)候調(diào)用+load方法,在main函數(shù)之前腌零。

+load方法可以繼承梯找。調(diào)用子類(lèi)的+load方法之前,會(huì)先調(diào)用父類(lèi)的+load方法益涧。一般不手動(dòng)調(diào)用+load方法初肉,而是讓系統(tǒng)去調(diào)用。如果手動(dòng)調(diào)用+load方法,就會(huì)按照消息發(fā)送機(jī)制牙咏,通過(guò)isa指針找到類(lèi)、元類(lèi)嘹裂,之后在方法列表中進(jìn)行查找妄壶。

4.4 load、initialize方法的區(qū)別寄狼?

  • 調(diào)用方式:
    • load根據(jù)函數(shù)地址直接調(diào)用丁寄。
    • initialize通過(guò)objc_msgSend調(diào)用。
  • 調(diào)用時(shí)機(jī):
    • load是runtime加載類(lèi)泊愧、分類(lèi)的時(shí)候調(diào)用伊磺,只會(huì)調(diào)用一次。
    • initialize是類(lèi)第一次接收消息時(shí)調(diào)用删咱,每個(gè)類(lèi)只會(huì) initialize 一次屑埋,但父類(lèi)的+initialize方法可能會(huì)被調(diào)用多次。

4.5 load痰滋、initialize調(diào)用順序摘能?

  • load
    1. 先調(diào)用類(lèi)的load。
      1. 先編譯的類(lèi)敲街,優(yōu)先調(diào)用团搞。
      2. 調(diào)用子類(lèi)load前會(huì)先調(diào)用父類(lèi)的load。
    2. 后調(diào)用分類(lèi)的load多艇。
      1. 先編譯的分類(lèi)逻恐,優(yōu)先調(diào)用。
  • initialize
    1. 先初始化父類(lèi)峻黍。
    2. 后初始化子類(lèi)复隆。如果子類(lèi)沒(méi)有實(shí)現(xiàn)+initialize方法,最終會(huì)調(diào)用父類(lèi)的+initialize方法奸披。

總結(jié)

Objective-C 提供了兩種自動(dòng)配置類(lèi)的方法昏名,類(lèi)加載時(shí)調(diào)用+load方法,對(duì)于需要讓代碼運(yùn)行非常早的情景非常有用阵面。但因?yàn)?code>+load方法調(diào)用太早轻局,其他類(lèi)可能未加載而產(chǎn)生危險(xiǎn)。

+initialize方法使用懶加載样刷,首次收到消息時(shí)才會(huì)調(diào)用仑扑,適用場(chǎng)景更廣泛。

Demo名稱(chēng):category置鼻、load镇饮、initialize的本質(zhì)
源碼地址:https://github.com/pro648/BasicDemos-iOS/tree/master/category、load箕母、initialize的本質(zhì)

參考資料:

  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/分類(lèi)category储藐、load俱济、initialize的本質(zhì)和源碼分析.md

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市钙勃,隨后出現(xiàn)的幾起案子蛛碌,更是在濱河造成了極大的恐慌,老刑警劉巖辖源,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蔚携,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡克饶,警方通過(guò)查閱死者的電腦和手機(jī)酝蜒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)矾湃,“玉大人亡脑,你說(shuō)我怎么就攤上這事≈拮穑” “怎么了远豺?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)坞嘀。 經(jīng)常有香客問(wèn)我躯护,道長(zhǎng),這世上最難降的妖魔是什么丽涩? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任棺滞,我火速辦了婚禮,結(jié)果婚禮上矢渊,老公的妹妹穿的比我還像新娘继准。我一直安慰自己,他們只是感情好矮男,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布移必。 她就那樣靜靜地躺著,像睡著了一般毡鉴。 火紅的嫁衣襯著肌膚如雪崔泵。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,736評(píng)論 1 312
  • 那天猪瞬,我揣著相機(jī)與錄音憎瘸,去河邊找鬼。 笑死陈瘦,一個(gè)胖子當(dāng)著我的面吹牛幌甘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼锅风,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼酥诽!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起皱埠,我...
    開(kāi)封第一講書(shū)人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤盆均,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后漱逸,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡游沿,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年饰抒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诀黍。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡袋坑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出眯勾,到底是詐尸還是另有隱情枣宫,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布吃环,位于F島的核電站也颤,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏郁轻。R本人自食惡果不足惜翅娶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望好唯。 院中可真熱鬧竭沫,春花似錦、人聲如沸骑篙。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)靶端。三九已至谎势,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間躲查,已是汗流浹背它浅。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留镣煮,地道東北人姐霍。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親镊折。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胯府,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容