Categroy底層原理

一勺择、Category概念?

Category是Objective-C 2.0之后添加的語(yǔ)言特性谬莹,分類陋率、類別其實(shí)都是指的Category教翩。Category的主要作用是為已經(jīng)存在的類添加方法沛简。

可以把類的實(shí)現(xiàn)分開在幾個(gè)不同的文件里面齐鲤,這樣做有幾個(gè)好處,如下
  • 1.減少單個(gè)文件的體積
  • 2.把不同的功能組織到不同的category里
  • 3.由多個(gè)開發(fā)者共同完成一個(gè)類
  • 4.按需加載想要的category
  • 5.聲明私有方法

二椒楣、Category源碼分析

RMPerson

#import <Foundation/Foundation.h>
@interface RMPerson : NSObject
@end

#import "RMPerson.h"
@implementation RMPerson
@end

RMPerson+(Test)

#import "RMPerson.h"

@interface RMPerson (Test) <NSCopying>
- (void)text;

+ (void)text1;

@property (nonatomic, assign) int age;
@property (nonatomic, assign) double weight;
@end
----------------------------------------------------------
#import "RMPerson+Test.h"
@implementation RMPerson (Test)
- (void)text {
    NSLog(@"TEST---111111111111");
}

+ (void)text1 {
    NSLog(@"TEST---222222222222");
}
@end

RMPerson類和RMPerson分類-RMPerson+(Test)给郊,我們通過xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc RMPerson+(Test).mRMPerson+(Test)轉(zhuǎn)換成C/C++源碼。窺探下源碼的內(nèi)容(由于內(nèi)容比較多捧灰,上重要的部分)

分類結(jié)構(gòu)體
struct _category_t {
    const char *name;  //類名稱
    struct _class_t *cls;  //類指針
    const struct _method_list_t *instance_methods; //對(duì)象方法列表
    const struct _method_list_t *class_methods; //類方法列表
    const struct _protocol_list_t *protocols; //協(xié)議方法列表
    const struct _prop_list_t *properties; //屬性列表
};
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
        // Discover categories. 
    for (EACH_HEADER) {
        category_t **catlist = 
            _getObjc2CategoryList(hi, &count);
        bool hasClassProperties = hi->info()->hasCategoryClassProperties();

        for (i = 0; i < count; i++) {
            category_t *cat = catlist[i];
            Class cls = remapClass(cat->cls);

            if (!cls) {
                // Category's target class is missing (probably weak-linked).
                // Disavow any knowledge of this category.
                catlist[i] = nil;
                if (PrintConnecting) {
                    _objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
                                 "missing weak-linked target class", 
                                 cat->name, cat);
                }
                continue;
            }


            // Process this category. 
            // First, register the category with its target class. 
            // Then, rebuild the class's method lists (etc) if 
            // the class is realized. 
            bool classExists = NO;
            if (cat->instanceMethods || cat->protocols || cat->instanceProperties)
            {
                addUnattachedCategoryForClass(cat, cls, hi);
                if (cls->isRealized()) {
                    remethodizeClass(cls);
                    classExists = YES;
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category -%s(%s) %s", 
                                 cls->nameForLogging(), cat->name, 
                                 classExists ? "on existing class" : "");
                }
            }

            if (cat->classMethods  || cat->protocols || (hasClassProperties && cat->_classProperties))
            {
                addUnattachedCategoryForClass(cat, cls->ISA(), hi);
                if (cls->ISA()->isRealized()) {
                    remethodizeClass(cls->ISA());
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category +%s(%s)", 
                                 cls->nameForLogging(), cat->name);
                }
            }
        }
    }
}

由上面源碼我們閱讀可得出

  • 1.將分類的對(duì)象方法淆九、對(duì)象協(xié)議方法、對(duì)象屬性整理到類對(duì)象中
  • 2.將分類的類方法整理到元類對(duì)象中
    而從源碼中毛俏,我們可注意到炭庙,無(wú)論哪種整理都是通過調(diào)用static void remethodizeClass(Class cls)函數(shù)來重新整理類的數(shù)據(jù),下面我們來看看remethodizeClass函數(shù)如何整理類信息
static void remethodizeClass(Class cls)
{
    category_list *cats;
    bool isMeta;

    runtimeLock.assertWriting();

    isMeta = cls->isMetaClass();

    // Re-methodizing: check for more categories
    if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
        if (PrintConnecting) {
            _objc_inform("CLASS: attaching categories to class '%s' %s", 
                         cls->nameForLogging(), isMeta ? "(meta)" : "");
        }
        // 附加分類
        attachCategories(cls, cats, true /*flush caches*/);        
        free(cats);
    }
}

這個(gè)函數(shù)的主要作用是將 Category 中的方法、屬性和協(xié)議整合到類(主類或元類)中煌寇,然后通過數(shù)據(jù)字段 data() 得到類對(duì)象里面的數(shù)據(jù)焕蹄,將 所有分類的對(duì)象方法、屬性阀溶、協(xié)議腻脏,通過attachCategoryMethods函數(shù)附加到類對(duì)象的方法列表中鸦泳,而attachCategoryMethods 函數(shù)才是正在處理Category方法的

static void attachCategories(Class cls, category_list *cats, bool flush_caches)
{
    if (!cats) return;
    if (PrintReplacedMethods) printReplacements(cls, cats);

    bool isMeta = cls->isMetaClass();

    // fixme rearrange to remove these intermediate allocations
    method_list_t **mlists = (method_list_t **)
        malloc(cats->count * sizeof(*mlists)); // 方法列表
    property_list_t **proplists = (property_list_t **) 
        malloc(cats->count * sizeof(*proplists)); // 屬性列表
    protocol_list_t **protolists = (protocol_list_t **)
        malloc(cats->count * sizeof(*protolists)); // 協(xié)議列表
    
    // Count backwards through cats to get newest categories first
    int mcount = 0;
    int propcount = 0;
    int protocount = 0;
    int i = cats->count; 
    bool fromBundle = NO;
    while (i--) {
        auto& entry = cats->list[i];

        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            mlists[mcount++] = mlist;  // 從最后編譯的分類開始取出
            fromBundle |= entry.hi->isBundle();
        }
        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            proplists[propcount++] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocols;
        if (protolist) {
            protolists[protocount++] = protolist;
        }
    }
    
    // 得到類對(duì)象里面的數(shù)據(jù)
    auto rw = cls->data();

    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
    // 將所有分類的對(duì)象方法,附加到類對(duì)象的方法列表中
    rw->methods.attachLists(mlists, mcount);
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls);
    
    // 將所有分類的屬性永品,附加到類對(duì)象的屬性列表中
    rw->properties.attachLists(proplists, propcount);
    free(proplists);
    
    //將所有分類的協(xié)議做鹰,附加到類對(duì)象的協(xié)議中
    rw->protocols.attachLists(protolists, protocount);
    free(protolists);
}

attachLists函數(shù)里主要的是memmove函數(shù)memcpy函數(shù)memmove函數(shù)將原來的方法往后移動(dòng)了addedCount(分類的方法數(shù)量)個(gè)位置鼎姐,memcpy函數(shù)將分類的方法添加到原來類方法列表的位置钾麸,這樣就完美將分類的方法、協(xié)議症见、屬性添加到了類信息中

    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;
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
            array()->count = newCount;
            // array()->lists 原來的方法列表
            memmove(array()->lists + addedCount,
                    array()->lists,
                    oldCount * sizeof(array()->lists[0]));
            // addedLists 所有分類的方法列表
            memcpy(array()->lists,
                   addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
        } 
        else {
            // 1 list -> many lists
            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;
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
    }

貼一下源碼的閱讀順序喂走,有興趣的同學(xué)可以下載源碼閱讀一下:
源碼解讀順序,如下

  • objc-os.mm
  • _objc_init
  • map_images
  • map_images_nolock
  • objc-runtime-new.mm
  • _read_images
  • remethodizeClass
  • attachCategories
  • attachLists
  • realloc谋作、memmove芋肠、 memcpy

總結(jié):

1.通過runtime加載某個(gè)類的所有Category數(shù)據(jù)
2.把所有Category的方法、屬性遵蚜、協(xié)議數(shù)據(jù)帖池,合并到一個(gè)大數(shù)組中,后面參與編輯的Category吭净,會(huì)在數(shù)組的前面睡汹。
3.將合并后的分類數(shù)據(jù)(方法、屬性寂殉、協(xié)議)囚巴,插入到類原來數(shù)據(jù)的前面
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市友扰,隨后出現(xiàn)的幾起案子彤叉,更是在濱河造成了極大的恐慌,老刑警劉巖村怪,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件秽浇,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡甚负,警方通過查閱死者的電腦和手機(jī)柬焕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來梭域,“玉大人斑举,你說我怎么就攤上這事〔≌牵” “怎么了懂昂?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我凌彬,道長(zhǎng)沸柔,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任铲敛,我火速辦了婚禮褐澎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘伐蒋。我一直安慰自己工三,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布先鱼。 她就那樣靜靜地躺著俭正,像睡著了一般。 火紅的嫁衣襯著肌膚如雪焙畔。 梳的紋絲不亂的頭發(fā)上掸读,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音宏多,去河邊找鬼儿惫。 笑死,一個(gè)胖子當(dāng)著我的面吹牛伸但,可吹牛的內(nèi)容都是我干的肾请。 我是一名探鬼主播,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼更胖,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼铛铁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起却妨,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤饵逐,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后管呵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體梳毙,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡哺窄,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年捐下,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片萌业。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡坷襟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出生年,到底是詐尸還是另有隱情婴程,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布抱婉,位于F島的核電站档叔,受9級(jí)特大地震影響桌粉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜衙四,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一铃肯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧传蹈,春花似錦押逼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至沾歪,卻和暖如春漂彤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背瞬逊。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工显歧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人确镊。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓士骤,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親蕾域。 傳聞我的和親對(duì)象是個(gè)殘疾皇子拷肌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

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