探究Category本质

细致的看了下Category的东西,记录一下。

Category用途:
1.进行类扩展
2.hook一个方法
3.重写已有类中的一个方法

跟着代码走不会错。
首先创建三个类分别是Person,Person+eat,Person+sleep。

//1 Person
@interface Person : NSObject
- (void)run;
@end

//2 Person+eat
@interface Person (eat)
- (void)eat;
@end

//3 Person+sleep
@interface Person (sleep)
- (void)sleep;
@end

cpp 重写 Person+eat 代码
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Person+eat.m -o Person+eat-arm64.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;
};

发现有一个 struct _category_t 类型的 _OBJC_$_CATEGORY_Person_$_eat

static struct _category_t _OBJC_$_CATEGORY_Person_$_eat __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
    "Person",
    0, // &OBJC_CLASS_$_Person,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_eat,
    0,
    0,
    0,
};

由于我只写了一个对象方法,所以变量中只有 _method_list_t

然后我们看看Category的源码:
https://opensource.apple.com/tarballs/ 找到 objc4,下载源码。

struct category_t {
    const char *name;
    classref_t cls;
    struct method_list_t *instanceMethods;
    struct method_list_t *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);
};

代码结构 和 cpp 重写的略有不同

结构看接口大概就知道什么意思,类名,对象方法列表,类对象方法列表,协议列表等等。

然后我们深入去看,类别如何将方法,属性合并到已有类中的。
1.objc-os.mm 文件
2.map_images方法
3.map_images_nolock方法
4._read_images方法
5.remethodizeClass 重新组织方法

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

点击 attachCategories 进入到方法中

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_t,method_t],[method_t,method_t]]
    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));

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

    //得到类对象的数据
    auto rw = cls->data();

    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
    
    //将所有分类的方法,附加到我们的类方法列表中
    rw->methods.attachLists(mlists, mcount);
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls);

    rw->properties.attachLists(proplists, propcount);
    free(proplists);

    rw->protocols.attachLists(protolists, protocount);
    free(protolists);
}

有详细的注释,主要注意的地方:
while (i--) 说明是后面的category 方法列表 先放到mlists数组里,cats->list顺序与 compile soure 的编译顺序相关。说明最后的分类,优先放到方法前面。

进入到 rw->methods.attachLists(mlists, mcount); 方法中,源码如下:

void attachLists(List* const * addedLists, uint32_t addedCount) {
    if (addedCount == 0) return;

    //addedCount 分类个数
    if (hasArray()) {
        // many lists -> many lists
        uint32_t oldCount = array()->count;
        uint32_t newCount = oldCount + addedCount;
        //realloc 重新创建 array(),大小是 类中原来的方法列表数量+categoory方法列表数量
        setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
        array()->count = newCount;
        //移动,将原来的方法列表移动到后面,移动了addedCount,相当于把分类方法列表的位置给空出来,其实index是
        memmove(array()->lists + addedCount, array()->lists, 
                oldCount * sizeof(array()->lists[0]));
        //将分类方法列表,拷贝到数组中,起始是0
        memcpy(array()->lists, addedLists, 
               addedCount * sizeof(array()->lists[0]));
        
    }
}

很关键的两个点:memmove,memcpy

memmove : [3,4,2,1] - > 右移2位 - > [3,4,3,4]。
可以完整的挪动3和4
memcpy:[3,4,2,1] - > 右移2位 - > [3,3,3,1]。
3移动到4,4位置变成3,4位置的3再移动到2位置,2位置的元素变成3,因此memcpy 会丢失原有的元素。

综上总结一下:
1.Category本质是个_category_t结构体
2.Category通过runtime动态将分类的方法合并到类对象、元类对象中
3.合并方法时,realloc 重新创建 array() (二维数组**method_lists),首先将原来的方法列表移动到后面,把Category的方法列表位置空出来,然后将Category_list的方法列表拷贝到array() 中。
4.Category_list 的顺序,与 commplie source 顺序有关。
5.对于同一个方法后加入的类别会覆盖先加入的类别中和类中的方法

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,021评论 8 265
  • 本文载自: http://blog.csdn.net/a316212802/article/details/49...
    MrLuckyluke阅读 2,428评论 1 7
  • 1.手掌脚掌又起紫色点点,四肢也有,头皮好痒,老是抓,晚上自己抓手抓脚,为什么?让大人给她抓手抓脚抓背,会不会继发...
    灵子灵阅读 168评论 0 0
  • 八部众的传说在远去,佛祖曾震慑八方,收服妖怪,因而世间得以安享太平。 常有天灾人祸,人们总是祈求神灵相助,却不知八...
    血海飞花阅读 291评论 0 0