category工作原理

摘要

在Objective-C 2.0中,提供了category這個語言特性,可以動態地為已有類添加新行為。如今category已經遍布于Objective-C代碼的各個角落,從Apple官方的framework到各個開源框架,從功能繁復的大型APP到簡單的應用,catagory無處不在。本文對category做了比較全面的整理,希望對讀者有所裨益。

目錄結構

1、 category簡介
2、 category結構組成
3、 category加載過程
4、category和+load

1、 category簡介

category是Objective-C 2.0之后添加的語言特性,category的主要作用是為已經存在的類添加方法。除此之外,apple還推薦了category的另外兩個使用場景1

  • 可以把類的實現分開在幾個不同的文件里面。這樣做有幾個顯而易見的好處,a)可以減少單個文件的體積 b)可以把不同的功能組織到不同的category里 c)可以由多個開發者共同完成一個類 d)可以按需加載想要的category 等等。
  • 聲明私有方法

不過除了apple推薦的使用場景,廣大開發者腦洞大開,還衍生出了category的其他幾個使用場景:

  • 模擬多繼承
  • 把framework的私有方法公開

Objective-C的這個語言特性對于純動態語言來說可能不算什么,比如JavaScript,你可以隨時為一個“類”或者對象添加任意方法和實例變量。但是對于不是那么“動態”的語言而言,這確實是一個了不起的特性。

2、 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;
};
  • name: 分類名字
  • cls: 所屬的class類
  • instance_methods: 實例方法列表
  • class_methods: 類方法列表
  • protocols: 協議列表
  • properties: 屬性列表

可見一個 category持有了一個method_list_t 類型的數組,method_list_t又繼承自 entsize_list_tt,這是一種泛型容器:

struct method_list_t : entsize_list_tt<method_t, method_list_t, 0x3> {
    // 成員變量和方法
};
template <typename element, typename list, uint32_t flagmask>
struct entsize_list_tt {
    uint32_t entsizeAndFlags;
    uint32_t count;
    Element first;
};</typename element, typename list, uint32_t flagmask></method_t, method_list_t, 0x3>
  • entsize_list_tt: 可以理解為一個容器,擁有自己的迭代器用于遍歷所有元素
  • Element: 元素類型
  • List: 用于指定容器類型
  • uint32_t flagmask: 標記位

category結構體構造中可以看到_method_list_t類型的方法列表,當類中有一個方法時的定義如下:

static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[1];
}

可以看到_method_list_t結構體中包含_objc_method類型方法列表,即存儲方法的容器,_objc_method定義:

struct _objc_method {
    struct objc_selector * _cmd;
    const char *method_type;
    void  *_imp;
}

以上是category結構體構造,最后,我們還有一個結構體 category_list 用來存儲所有的 category,它的定義如下:

struct locstamped_category_list_t {
    uint32_t count;
    locstamped_category_t list[0];
};
struct locstamped_category_t {
    category_t *cat;
    struct header_info *hi;
};
typedef locstamped_category_list_t category_list;

除了標記存儲的 category 的數量外,locstamped_category_list_t 結構體還聲明了一個長度為零的數組,這其實是 C99 中的一種寫法,允許我們在運行期動態的申請內存。

3、category加載過程

在分析category加載過程之前,我們先通過一段代碼看下category內部實現:
oc代碼:

//.h
#import <Foundation/Foundation.h>

@interface Person : NSObject
- (void)printName;
@property(nonatomic, copy) NSString *name;
@end

@interface Person(PersonAddtion)
@property(nonatomic, copy) NSString *name;
- (void)printName;
@end

//.m
#import "Person.h"
@implementation Person
- (void)printName{
    NSLog(@"Person - printName");
}
@end

@implementation Person(PersonAddtion)
- (void)printName{
    NSLog(@"PersonAddtion - printName");
}
@end

我們使用clang的命令clang -rewrite-objc Person.m去看看category到底會變成什么。
我們得到了一個3M大小,1w行的.cpp文件,我們忽略掉所有和我們無關的東西,在文件的最后,我們找到了如下代碼片段:

//這是Person類的代碼
//這是Person類的代碼
static struct /*_ivar_list_t*/ {
    unsigned int entsize;  // sizeof(struct _prop_t)
    unsigned int count;
    struct _ivar_t ivar_list[1];
} _OBJC_$_INSTANCE_VARIABLES_Person __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_ivar_t),
    1,
    {{(unsigned long int *)&OBJC_IVAR_$_Person$_name, "_name", "@\"NSString\"", 3, 8}}
};

static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[3];
} _OBJC_$_INSTANCE_METHODS_Person __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_objc_method),
    3,
    {{(struct objc_selector *)"printName", "v16@0:8", (void *)_I_Person_printName},
    {(struct objc_selector *)"name", "@16@0:8", (void *)_I_Person_name},
    {(struct objc_selector *)"setName:", "v24@0:8@16", (void *)_I_Person_setName_}}
};

static struct /*_prop_list_t*/ {
    unsigned int entsize;  // sizeof(struct _prop_t)
    unsigned int count_of_properties;
    struct _prop_t prop_list[1];
} _OBJC_$_PROP_LIST_Person __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_prop_t),
    1,
    {{"name","T@\"NSString\",C,N,V_name"}}
};

static struct _class_ro_t _OBJC_METACLASS_RO_$_Person __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    1, sizeof(struct _class_t), sizeof(struct _class_t), 
    (unsigned int)0, 
    0, 
    "Person",
    0, 
    0, 
    0, 
    0, 
    0, 
};

static struct _class_ro_t _OBJC_CLASS_RO_$_Person __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    0, __OFFSETOFIVAR__(struct Person, _name), sizeof(struct Person_IMPL), 
    (unsigned int)0, 
    0, 
    "Person",
    (const struct _method_list_t *)&_OBJC_$_INSTANCE_METHODS_Person,
    0, 
    (const struct _ivar_list_t *)&_OBJC_$_INSTANCE_VARIABLES_Person,
    0, 
    (const struct _prop_list_t *)&_OBJC_$_PROP_LIST_Person,
};

//這是PersonAddtion中實現代碼
//這是PersonAddtion中實現代碼
static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[1];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_PersonAddtion __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_objc_method),
    1,
    {{(struct objc_selector *)"printName", "v16@0:8", (void *)_I_Person_PersonAddtion_printName}}
};

static struct /*_prop_list_t*/ {
    unsigned int entsize;  // sizeof(struct _prop_t)
    unsigned int count_of_properties;
    struct _prop_t prop_list[1];
} _OBJC_$_PROP_LIST_Person_$_PersonAddtion __attribute__ ((used, section ("__DATA,__objc_const"))) = {
    sizeof(_prop_t),
    1,
    {{"name","T@\"NSString\",C,N"}}
};

extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_Person;

static struct _category_t _OBJC_$_CATEGORY_Person_$_PersonAddtion __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
    "Person",
    0, // &OBJC_CLASS_$_Person,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_PersonAddtion,
    0,
    0,
    (const struct _prop_list_t *)&_OBJC_$_PROP_LIST_Person_$_PersonAddtion,
};
static void OBJC_CATEGORY_SETUP_$_Person_$_PersonAddtion(void ) {
    _OBJC_$_CATEGORY_Person_$_PersonAddtion.cls = &OBJC_CLASS_$_Person;
}
#pragma section(".objc_inithooks$B", long, read, write)
__declspec(allocate(".objc_inithooks$B")) static void *OBJC_CATEGORY_SETUP[] = {
    (void *)&OBJC_CATEGORY_SETUP_$_Person_$_PersonAddtion,
};
static struct _class_t *L_OBJC_LABEL_CLASS_$ [1] __attribute__((used, section ("__DATA, __objc_classlist,regular,no_dead_strip")))= {
    &OBJC_CLASS_$_Person,
};
static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= {
    &_OBJC_$_CATEGORY_Person_$_PersonAddtion,
};

從以上兩段代碼可以看出:

  • Person類中生成了_name變量、printName方法、name的getter方法、setName方法、name屬性
  • PersonAddtion類中僅僅有printName方法、name屬性

以上就可以看出category中并不會生成實例變量,所以在category中不能使用實例變量.

接著對以上PersonAddtion代碼分析:

  • 首先編譯器生成了實例方法列表_OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_PersonAddtion和屬性列表_OBJC_$_PROP_LIST_Person_$_PersonAddtion,兩者的命名都遵循了公共前綴+類名+category名字的命名方式,而且實例方法列表里面填充的正是我們在PersonAddtion這個category里面寫的方法printName,而屬性列表里面填充的也正是我們在PersonAddtio里添加的name屬性。還有一個需要注意到的事實就是category的名字用來給各種列表以及后面的category結構體本身命名,而且有static來修飾,所以在同一個編譯單元里我們的category名不能重復,否則會出現編譯錯誤。
  • 編譯器生成了category本身_OBJC_$_CATEGORY_Person_$_PersonAddtion,并用前面生成的列表來初始化category本身。
  • 編譯器在DATA段下的objc_catlist section里保存了一個大小為1的category_t的數組L_OBJC_LABEL_CATEGORY_$ [1](當然,如果有多個category,會生成對應長度的數組,用于運行期category的加載。
接下來我們看下category如何加載?

我們知道,Objective-C的運行是依賴OC的runtime的,而OC的runtime和其他系統庫一樣,是OS X和iOS通過dyld動態加載的。
對于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);
}

以上方法加載過程:

void _objc_init(void)
└──const char *map_2_images(...)
    └──const char *map_images_nolock(...)
        └──void _read_images(header_info **hList, uint32_t hCount)

category被附加到類上面是在map_images的時候發生的,在new-ABI的標準下,_objc_init里面的調用的map_images最終會調用objc-runtime-new.mm里面的_read_images方法,而在_read_images方法的結尾,有以下的代碼片段:

// Discover categories. 
    for (EACH_HEADER) {
        category_t **catlist =
            _getObjc2CategoryList(hi, &count);
        for (i = 0; i < count; i++) {
            category_t *cat = catlist[i];
            class_t *cls = remapClass(cat->cls);

            if (!cls) {
                // Category's target class is missing (probably weak-linked).
                // Disavow any knowledge of this category.
                catlist[i] = NULL;
                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 (isRealized(cls)) {
                    remethodizeClass(cls);
                    classExists = YES;
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category -%s(%s) %s",
                                 getName(cls), cat->name,
                                 classExists ? "on existing class" : "");
                }
            }

            if (cat->classMethods  ||  cat->protocols 
                /* ||  cat->classProperties */)
            {
                addUnattachedCategoryForClass(cat, cls->isa, hi);
                if (isRealized(cls->isa)) {
                    remethodizeClass(cls->isa);
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category +%s(%s)",
                                 getName(cls), cat->name);
                }
            }
        }
    }

這段代碼很容易理解:

  • 把category的實例方法、協議以及屬性添加到類上
  • 把category的類方法和協議添加到類的metaclass上

在上述的代碼片段里,addUnattachedCategoryForClass只是把類和category做一個關聯映射,而remethodizeClass才是真正去處理添加事宜的功臣,remethodizeClass實現:

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);
    }
}

而對于添加類的實例方法而言,又會去調用attachCategories這個方法,我們去看下attachCategories:

static void attachCategories(Class cls, category_list *cats, bool flush_caches) {
    if (!cats) return;
    bool isMeta = cls->isMetaClass();
    method_list_t **mlists = (method_list_t **)malloc(cats->count * sizeof(*mlists));
    // Count backwards through cats to get newest categories first
    int mcount = 0;
    int i = cats->count;
    while (i--) {
        auto& entry = cats->list[i];
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            mlists[mcount++] = mlist;
        }
    }
    auto rw = cls->data();
    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
    rw->methods.attachLists(mlists, mcount);
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls);
}

以上調用過程如下:

void _read_images(header_info **hList, uint32_t hCount)
└──static void remethodizeClass(Class cls)
    └──static void attachCategories(Class cls, category_list *cats, bool flush_caches)

首先,通過 while 循環,我們遍歷所有的 category,也就是參數 cats 中的 list 屬性。對于每一個 category,得到它的方法列表 mlist 并存入 mlists 中。

換句話說,我們將所有 category 中的方法拼接到了一個大的二維數組中,數組的每一個元素都是裝有一個 category 所有方法的容器。這句話比較繞,但你可以把 mlists 理解為文章開頭所說,舊版本的 objc_method_list **methodLists。

在 while 循環外,我們得到了拼接成的方法,此時需要與類原來的方法合并:

auto rw = cls->data();
rw->methods.attachLists(mlists, mcount);

這兩行代碼讀不懂是必然的,因為在 Objective-C 2.0 時代,對象的內存布局已經發生了一些變化。我們需要先了解對象的布局模型才能理解這段代碼。

Objective-C 2.0 對象布局模型

我們主要看下一下三個概念:

1、 objc_class
2、 class_data_bits_t
3、 class_rw_t

  • objc_class

相信讀到這里的大部分讀者都學習過文章開頭所說的對象布局模型,因此在這一部分,我們采用類比的方法,來看看 Objective-C 2.0 下發生了哪些改變。

首先,Class 和 id 指針的定義并沒有發生改變,他們一個指向類對應的結構體,一個指向對象對應的結構體:

// objc.h
typedef struct objc_class *Class;
typedef struct objc_object *id;

比較有意思的一點是,objc_class 結構體是繼承自 objc_object的:

struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};
struct objc_class : objc_object {
    Class superclass;
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
    class_rw_t *data() {
        return bits.data();
    }
};

這一點也很容易理解,早在 Objective-C 1.0 時代,我們就知道一個對象的結構體只有 isa 指針,指向它所屬的類。而類的結構體也有 isa 指針指向它的元類.

可見 Objective-C 1.0 的布局模型中,cachesuper_class 被原封不動的移過來了,而剩下的屬性則似乎消失不見。取而代之的是一個 bits屬性,以及 data() 方法,這個方法調用的其實是 bits 屬性的data()方法,并返回了一個 class_rw_t類型的結構體指針。

  • class_data_bits_t

以下是簡化版 class_data_bits_t 結構體的定義:

struct class_data_bits_t {
    uintptr_t bits;
public:
    class_rw_t* data() {
        return (class_rw_t *)(bits & FAST_DATA_MASK);
    }
}

可見這個結構體只有一個 64 位的 bits 成員,存儲了一個指向 class_rw_t 結構體的指針和三個標志位。它實際上由三部分組成。首先由于 Mac OS X 只使用 47 位內存地址,所以前 17 位空余出來,提供給 retain/release 和 alloc/dealloc 方法使用,做一些優化。其次,由于內存對齊,指針地址的后三位都是 0,因此可以用來做標志位:

// class is a Swift class
#define FAST_IS_SWIFT           (1UL<<0)
// class or superclass has default retain/release/autorelease/retainCount/
//   _tryRetain/_isDeallocating/retainWeakReference/allowsWeakReference
#define FAST_HAS_DEFAULT_RR     (1UL<<1)
// class's instances requires raw isa
#define FAST_REQUIRES_RAW_ISA   (1UL<<2)
// data pointer
#define FAST_DATA_MASK          0x00007ffffffffff8UL

如果計算一下就會發現,FAST_DATA_MASK 這個 16 進制常量的二進制表示恰好后三位為0,且長度為47位: 11111111111111111111111111111111111111111111000,我們通過這個掩碼做按位與運算即可取出正確的指針地址。

引用 Draveness 在 深入解析 Objective-C 中方法的結構 中的圖片做一個總結:

  • class_rw_t

bits 中包含了一個指向 class_rw_t結構體的指針,它的定義如下:

struct class_rw_t {
    uint32_t flags;
    uint32_t version;
    const class_ro_t *ro;
    method_array_t methods;
    property_array_t properties;
    protocol_array_t protocols;
}

注意到有一個名字很類似的結構體 class_ro_t,這里的rwro分別表示 readwritereadonly。因為 class_ro_t存儲了一些由編譯器生成的常量。

正是由于 class_ro_t中的兩個屬性instanceStartinstanceSize的存在,保證了 Objective-C2.0 的 ABI 穩定性。因為即使父類增加方法,子類也可以在運行時重新計算 ivar 的偏移量,從而避免重新編譯。

我們回頭接著分析代碼:

auto rw = cls->data();
rw->methods.attachLists(mlists, mcount);

現在來看,rw 是一個 class_rw_t 類型的結構體指針。根據 runtime 中的數據結構,它有一個 methods 結構體成員,并從父類繼承了 attachLists 方法,用來合并 category 中的方法:

void attachLists(List* const * addedLists, uint32_t addedCount) {
    if (addedCount == 0) return;
    uint32_t oldCount = array()->count;
    uint32_t newCount = oldCount + addedCount;
    setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
    array()->count = newCount;
    memmove(array()->lists + addedCount, array()->lists, oldCount * sizeof(array()->lists[0]));
    memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
}

在實際代碼中,比上面略復雜一些。因為為了提高性能,蘋果做了一些優化,比如當 List 處于第二種狀態(只有一個指針,指向一個元數據的集合)時,其實并不需要在原地擴容空間,而是只要重新申請一塊內存,并將最后一個位置留給原來的集合即可。

這樣只多花費了很少的內存空間,也就是原來二維數組占用的內存空間,但是 malloc() 的性能優勢會更加明顯,這其實是一個空間換時間的權衡問題。

需要注意的是,無論執行哪種邏輯,參數列表中的方法都會被添加到二維數組的前面。而我們簡單的看一下 runtime 在查找方法時的邏輯:

static method_t *getMethodNoSuper_nolock(Class cls, SEL sel){
    for (auto mlists = cls->data()->methods.beginLists(),
              end = cls->data()->methods.endLists();
         mlists != end;
         ++mlists) {
        method_t *m = search_method_list(*mlists, sel);
        if (m) return m;
    }
    return nil;
}
static method_t *search_method_list(const method_list_t *mlist, SEL sel) {
    for (auto& meth : *mlist) {
        if (meth.name == sel) return &meth;
    }
}

可見搜索的過程是按照從前向后的順序進行的,一旦找到了就會停止循環。因此 category 中定義的同名方法不會替換類中原有的方法,但是對原方法的調用實際上會調用 category 中的方法。

4、-category和+load方法

我們知道,在類和category中都可以有+load方法,那么有兩個問題:

  • 在類的+load方法調用的時候,我們可以調用category中聲明的方法么?
  • 這么些個+load方法,調用順序是咋樣的呢?

鑒于上述幾節我們看的代碼太多了,對于這兩個問題我們先來看一點直觀的:


我們的代碼里有Person和Person的兩個category (Category1和Category2),Person和兩個category都添加了+load方法,并且Category1和Category2都寫了Person的printName方法。
在Xcode中點擊Edit Scheme,添加如下兩個環境變量(可以在執行load方法以及加載category的時候打印log信息,更多的環境變量選項可參見objc-private.h):


即:OBJC_PRINT_LOAD_METHODSOBJC_PRINT_REPLACED_METHODS
運行項目,我們會看到控制臺打印很多東西出來,我們只找到我們想要的信息,順序如下:

objc[85057]: REPLACED: -[Person printName]  by category Category1 
objc[85057]: REPLACED: -[Person printName]  by category Category2
objc[85057]: LOAD: class 'Person' scheduled for +load
objc[85057]: LOAD: category 'Person(Category1)' scheduled for +load
objc[85057]: LOAD: category 'Person(Category2)' scheduled for +load
objc[85057]: LOAD: +[Person load]
objc[85057]: LOAD: +[Person(Category1) load]
objc[85057]: LOAD: +[Person(Category2) load]

所以,對于上面兩個問題,答案是很明顯的:
1)、可以調用,因為附加category到類的工作會先于+load方法的執行
2)、+load的執行順序是先類,后category,而category+load執行順序是根據編譯順序決定的。
目前的編譯順序是這樣的:

我們調整一個Category1和Category2的編譯順序,run。ok,我們可以看到控制臺的輸出順序變了:

objc[85494]: REPLACED: -[Person printName]  by category Category2
objc[85494]: REPLACED: -[Person printName]  by category Category1
objc[85494]: LOAD: class 'Person' scheduled for +load
objc[85494]: LOAD: category 'Person(Category2)' scheduled for +load
objc[85494]: LOAD: category 'Person(Category1)' scheduled for +load
objc[85494]: LOAD: +[Person load]
objc[85494]: LOAD: +[Person(Category2) load]
objc[85494]: LOAD: +[Person(Category1) load]

雖然對于+load的執行順序是這樣,但是對于“覆蓋”掉的方法,則會先找到最后一個編譯的category里的對應方法。
那么怎么調用到原來類中被category覆蓋掉的方法?
對于這個問題,我們已經知道category其實并不是完全替換掉原來類的同名方法,只是category在方法列表的前面而已,所以我們只要順著方法列表找到最后一個對應名字的方法,就可以調用原來類的方法:

Person currentClass = [Person class];
Person *per = [[Person 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(per,lastSel);
    }
    free(methodList);
}

參考資料:
結合 category 工作原理分析 OC2.0 中的 runtime
iOS category內部實現原理

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 轉至元數據結尾創建: 董瀟偉,最新修改于: 十二月 23, 2016 轉至元數據起始第一章:isa和Class一....
    40c0490e5268閱讀 1,768評論 0 9
  • 本文載自: http://blog.csdn.net/a316212802/article/details/49...
    MrLuckyluke閱讀 2,484評論 1 7
  • 摘要 無論一個類設計的多么完美,在未來的需求演進中,都有可能會碰到一些無法預測的情況。那怎么擴展已有的類呢?一般而...
    癲癲的戀了閱讀 1,060評論 0 6
  • 這篇文章完全是基于南峰子老師博客的轉載 這篇文章完全是基于南峰子老師博客的轉載 這篇文章完全是基于南峰子老師博客的...
    西木閱讀 30,620評論 33 466
  • 本文詳細整理了 Cocoa 的 Runtime 系統的知識,它使得 Objective-C 如虎添翼,具備了靈活的...
    lylaut閱讀 823評論 0 4