iOS中的Category詳解

簡介

當(dāng)我們功能越來越多時公浪,單一文件的體積就會變大他宛,甚至臃腫。而多人配合開發(fā)一個文件時因悲,還會出現(xiàn)不少沖突堕汞,這時就要用相應(yīng)的解決方法,就是category晃琳。
這篇文章將會從幾個方向出發(fā)讯检,詳細的了解category的實現(xiàn)機制。

1. category簡介卫旱。
2. category與extension的區(qū)別
3. category如何加載并且添加到類
4. category對象關(guān)聯(lián)

category簡介

category是在2.0之后添加的特性人灼,作用是可以為存在的文件添加方法,我們列舉幾個常用的場景:

1. 模擬多繼承
2. 將私有API公開
3. 將一個類中的代碼分散出來管理
4. 私有方法
5. ......

category有很多可以挖掘的地方顾翼,下面我們就來一步一步揭開它的面紗

category與extension的區(qū)別

extension是在編譯期決定投放,category由運行期決定,這就是他們不同的根本之處适贸。它決定了他們之間的分工與區(qū)別灸芳。

extension的生命周期跟隨主類,用于隱藏私有信息拜姿,你必須擁有這個類的實現(xiàn)/源碼烙样,你才可以為它添加extension。見extension

category無法添加實例變量蕊肥,在運行期間谒获,對象內(nèi)存布局已經(jīng)確認,這時你無法破壞已經(jīng)存在的內(nèi)存空間壁却,所以無法進行實例變量的添加批狱。

category如何加載并且添加到類

在OC的runtime層中,都是用struct來表示展东,category由結(jié)構(gòu)體category_t表示赔硫,(objc-runtime-new.h中可以找到),

typedef struct category_t {
    const char *name;  //類名
    classref_t cls;  //類
    struct method_list_t *instanceMethods;  //添加的實例方法列表
    struct method_list_t *classMethods;  //添加的類方法列表
    struct protocol_list_t *protocols;  //添加的協(xié)議列表
    struct property_list_t *instanceProperties;  //添加的所有屬性
} category_t;

那么category如何加載盐肃?
在OC運行時中卦停,入口方法如下(在objc-os.mm)

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();
    lock_init();
    exception_init();

    // Register for unmap first, in case some +load unmaps something
    _dyld_register_func_for_remove_image(&unmap_image);
    dyld_register_image_state_change_handler(dyld_image_state_bound,
                                             1/*batch*/, &map_images);
    dyld_register_image_state_change_handler(dyld_image_state_dependents_initialized, 0/*not batch*/, &load_images);
}

category被附加到類上面是在map_images時發(fā)送,在new-ABI的標(biāo)準下恼蓬,map_images最終會調(diào)用objc-runtime-new.mm文件中_read_images方法惊完,我們來看一下:

void _read_images(header_info **hList, uint32_t hCount)
{
    ...
        _free_internal(resolvedFutureClasses);
    }

    // Discover categories. 
    for (EACH_HEADER) {
        category_t **catlist =
            _getObjc2CategoryList(hi, &count);
        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
                /* ||  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);
                }
            }
        }
    }

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

    // +load handled by prepare_load_methods()

    ...
}

這里我們可以看出

  1. 將category的實例方法、屬性添加到主類中
  2. 將category的類方法添加到元類(metaclass)中

無論哪種情況处硬,最后都是通過調(diào)用static void remethodizeClass(Class cls)函數(shù)來重新整理類數(shù)據(jù)小槐。

static void remethodizeClass(class_t *cls)
{
    category_list *cats;
    BOOL isMeta;

    rwlock_assert_writing(&runtimeLock);

    isMeta = isMetaClass(cls);

    // Re-methodizing: check for more categories
    if ((cats = unattachedCategoriesForClass(cls))) {
        chained_property_list *newproperties;
        const protocol_list_t **newprotos;

        if (PrintConnecting) {
            _objc_inform("CLASS: attaching categories to class '%s' %s",
                         getName(cls), isMeta ? "(meta)" : "");
        }

        // Update methods, properties, protocols

        BOOL vtableAffected = NO;
        attachCategoryMethods(cls, cats, &vtableAffected);

        newproperties = buildPropertyList(NULL, cats, isMeta);
        if (newproperties) {
            newproperties->next = cls->data()->properties;
            cls->data()->properties = newproperties;
        }

        newprotos = buildProtocolList(cats, NULL, cls->data()->protocols);
        if (cls->data()->protocols  &&  cls->data()->protocols != newprotos) {
            _free_internal(cls->data()->protocols);
        }
        cls->data()->protocols = newprotos;

        _free_internal(cats);

        // Update method caches and vtables
        flushCaches(cls);
        if (vtableAffected) flushVtables(cls);
    }
}

此函數(shù)的作用是將category中的方法、屬性、協(xié)議整合到主類/元類中凿跳,更新數(shù)據(jù)字段 data()中的 method_lists件豌、properties、protocols控嗜, 對于添加實例方法茧彤,則會調(diào)用 attachCategoryMethods

static void 
attachCategoryMethods(class_t *cls, category_list *cats,
                      BOOL *inoutVtablesAffected)
{
    if (!cats) return;
    if (PrintReplacedMethods) printReplacements(cls, cats);

    BOOL isMeta = isMetaClass(cls);
    method_list_t **mlists = (method_list_t **)
        _malloc_internal(cats->count * sizeof(*mlists));

    // Count backwards through cats to get newest categories first
    int mcount = 0;
    int i = cats->count;
    BOOL fromBundle = NO;
    while (i--) {
        method_list_t *mlist = cat_method_list(cats->list[i].cat, isMeta);
        if (mlist) {
            mlists[mcount++] = mlist;
            fromBundle |= cats->list[i].fromBundle;
        }
    }

    attachMethodLists(cls, mlists, mcount, NO, fromBundle, inoutVtablesAffected);

    _free_internal(mlists);

}

它的工作可以看成將category的實例方法列表拼成一個實例方法列表疆栏,然后調(diào)用attachMethodLists進行處理曾掂。

for (uint32_t m = 0;
             (scanForCustomRR || scanForCustomAWZ)  &&  m < mlist->count;
             m++)
        {
            SEL sel = method_list_nth(mlist, m)->name;
            if (scanForCustomRR  &&  isRRSelector(sel)) {
                cls->setHasCustomRR();
                scanForCustomRR = false;
            } else if (scanForCustomAWZ  &&  isAWZSelector(sel)) {
                cls->setHasCustomAWZ();
                scanForCustomAWZ = false;
            }
        }

        // Fill method list array
        newLists[newCount++] = mlist;
    .
    .
    .

    // Copy old methods to the method list array
    for (i = 0; i < oldCount; i++) {
        newLists[newCount++] = oldLists[i];
    }

這里我們需要注意,category并沒有完全的替換掉原有類的同名方法壁顶,category的方法被放置在新方法列表的前面珠洗,而原來類的方法被放到后面,在runtime中若专,遍歷方法列表查找時许蓖,找到了category的方法后,就會停止遍歷调衰,這就是我們平時所說的“覆蓋”方法膊爪。

找到源方法很簡單,只需要遍歷方法列表嚎莉,找到最后的一個對應(yīng)名字方法即可蚁飒,(摘自:美團技術(shù)博客)

Class currentClass = [MyClass class];
MyClass *my = [[MyClass alloc] init];

if (currentClass) {
    unsigned int methodCount;
    Method *methodList = class_copyMethodList(currentClass, &methodCount);
    IMP lastImp = NULL;
    SEL lastSel = NULL;
    for (NSInteger i = 0; i < methodCount; i++) {
        Method method = methodList[i];
        NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(method)) 
                                        encoding:NSUTF8StringEncoding];
        if ([@"printName" isEqualToString:methodName]) {
            lastImp = method_getImplementation(method);
            lastSel = method_getName(method);
        }
    }
    typedef void (*fn)(id,SEL);

    if (lastImp != NULL) {
        fn f = (fn)lastImp;
        f(my,lastSel);
    }
    free(methodList);
}

category對象關(guān)聯(lián)

那么當(dāng)在 category 中使用對象關(guān)聯(lián),那么相應(yīng)的存儲位置萝喘,生命周期是怎么樣的?
去探索一下源碼琼懊,在objc-references.mm文件中void _object_set_associative_reference方法

void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {
    // retain the new value (if any) outside the lock.
    ObjcAssociation old_association(0, nil);
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i != associations.end()) {
                // secondary table exists
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else {
                // create the new association (first time).
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects();
            }
        } else {
            // setting the association to nil breaks the association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i !=  associations.end()) {
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    refs->erase(j);
                }
            }
        }
    }
    // release the old value (outside of the lock).
    if (old_association.hasValue()) ReleaseValue()(old_association);
}

我們可以看出捂掰,關(guān)聯(lián)對象是由AssociationsManager管理仔雷,那么它是什么呢?

/ class AssociationsManager manages a lock / hash table singleton pair.
// Allocating an instance acquires the lock, and calling its assocations()
// method lazily allocates the hash table.

spinlock_t AssociationsManagerLock;

class AssociationsManager {
    // associative references: object pointer -> PtrPtrHashMap.
    static AssociationsHashMap *_map;
public:
    AssociationsManager()   { AssociationsManagerLock.lock(); }
    ~AssociationsManager()  { AssociationsManagerLock.unlock(); }
    
    AssociationsHashMap &associations() {
        if (_map == NULL)
            _map = new AssociationsHashMap();
        return *_map;
    }
};

AssociationsHashMap *AssociationsManager::_map = NULL;

AssociationsManager 是一個靜態(tài)的全局 AssociationsHashMap,用來存儲所有的關(guān)聯(lián)對象驱闷,key是對象的內(nèi)存地址,value則是另一個 AssociationsHashMap雇毫,其中存儲了關(guān)聯(lián)對象的kv恒界,對象銷毀的工作則交給 objc_destructInstance

void *objc_destructInstance(id obj) 
{
    if (obj) {
        Class isa_gen = _object_getClass(obj);
        class_t *isa = newcls(isa_gen);

        // Read all of the flags at once for performance.
        bool cxx = hasCxxStructors(isa);
        bool assoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen);

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        if (assoc) _object_remove_assocations(obj);

        if (!UseGC) objc_clear_deallocating(obj);
    }

    return obj;
}

如有錯誤請指正~

參考鏈接:
https://tech.meituan.com/DiveIntoCategory.html
http://blog.leichunfeng.com/blog/2015/05/18/objective-c-category-implementation-principle/
https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Category.html#//apple_ref/doc/uid/TP40008195-CH5-SW1 http://stackoverflow.com/questions/5272451/overriding-methods-using-categories-in-objective-c

這里可以看到源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市车胡,隨后出現(xiàn)的幾起案子檬输,更是在濱河造成了極大的恐慌,老刑警劉巖匈棘,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件丧慈,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機逃默,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門鹃愤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人完域,你說我怎么就攤上這事软吐。” “怎么了吟税?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵凹耙,是天一觀的道長。 經(jīng)常有香客問我乌妙,道長使兔,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任藤韵,我火速辦了婚禮虐沥,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘泽艘。我一直安慰自己欲险,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布匹涮。 她就那樣靜靜地躺著天试,像睡著了一般。 火紅的嫁衣襯著肌膚如雪然低。 梳的紋絲不亂的頭發(fā)上喜每,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機與錄音雳攘,去河邊找鬼带兜。 笑死,一個胖子當(dāng)著我的面吹牛吨灭,可吹牛的內(nèi)容都是我干的刚照。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼喧兄,長吁一口氣:“原來是場噩夢啊……” “哼无畔!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起吠冤,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤浑彰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后拯辙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體闸昨,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了饵较。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拍嵌。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖循诉,靈堂內(nèi)的尸體忽然破棺而出横辆,到底是詐尸還是另有隱情,我是刑警寧澤茄猫,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布狈蚤,位于F島的核電站,受9級特大地震影響划纽,放射性物質(zhì)發(fā)生泄漏脆侮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一勇劣、第九天 我趴在偏房一處隱蔽的房頂上張望靖避。 院中可真熱鬧,春花似錦比默、人聲如沸幻捏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽篡九。三九已至,卻和暖如春醋奠,著一層夾襖步出監(jiān)牢的瞬間榛臼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工窜司, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留沛善,地道東北人。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓例证,卻偏偏與公主長得像,于是被迫代替她去往敵國和親迷捧。 傳聞我的和親對象是個殘疾皇子织咧,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,619評論 2 354

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