分类(Category)

分类做了哪些事情?

  1. 声明私有方法
  2. 分解体积庞大的类文件
  3. 把Framework的私有方法公开化
  4. 可以添加实例方法, 类方法, 协议, 属性(只添加了get/set方法, 没有添加实例变量)

分类的特点

  1. 分类运行时决议,在运行时通过runTime把方法等添加到宿主类上. [扩展是编译时决议, 这是扩展和分类的最大区别]
  2. 分类可以给系统类添加分类[不能给系统类添加扩展]
  3. 分类可以添加:
  • 实例方法,
  • 类方法,
  • 协议,
  • 属性(只添加了get/set方法, 没有添加实例变量)
  • 可通过关联对象添加实例变量

分类的结构体

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);
};
  • 注意: 结构体中没有关于实例变量的成员结构

分类加载调用栈

  • 注意: image在这里表示镜像, 程序镜像或者内存镜像
static void remethodizeClass(Class cls)
{
    category_list *cats;
    bool isMeta;

    runtimeLock.assertLocked();

/*
我们分析分类单重实例方法的添加逻辑
因此在这里我们假设 isMeta = NO
*/
    isMeta = cls->isMetaClass();

    // Re-methodizing: check for more categories
//获取cls中未完成整合的所有类
    if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
        if (PrintConnecting) {
            _objc_inform("CLASS: attaching categories to class '%s' %s", 
                         cls->nameForLogging(), isMeta ? "(meta)" : "");
        }
        
//将分类cats拼接到cls上
        attachCategories(cls, cats, true /*flush caches*/);        
        free(cats);
    }
}
static void 
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
    if (!cats) return;//如果无分类, 直接返回
    if (PrintReplacedMethods) printReplacements(cls, cats);

/*
我们分析分类单重实例方法的添加逻辑
因此在这里我们假设 isMeta = NO
*/
    bool isMeta = cls->isMetaClass();
/*二维数组
[[method_t, method_t...], [method_t],[method_t, method_t, method_t]]
*/
    // 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));//协议列表

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

//获取宿主类当中rw数据, 其中包含宿主类的方法列表信息
    auto rw = cls->data();

//主要针对分类中有关内存管理相关方法情况下的一些特殊处理
    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);

/*
rw:代表类
methods:类的方法列表
attachLists:将含有mcount个元素的mlists拼接到rw的methods上
[即添加到宿主类上, 这就是说为什么分类是运行时决议]
*/
    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);
}
/*
addedLists:上一步传过来二维数组
[[method_t, method_t...], [method_t],[method_t, method_t, method_t]]
---------A分类方法列表-----  ----B---- ---------C----------
addedCount = 3
*/
    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;//重新设置元素个数

/*
内存移动
[[A], [B],[C],[原来第一个],[原来第二个]]
*/
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));

/*
内存拷贝
[[A]-->[addedLists第一个元素]
 [B],-->[addedLists第二个元素]
[C],-->[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]));
        }
    }
1. 分类方法会"覆盖"宿主类方法原因(其实分类方法和原宿主类方法都存在)

答: 通过memove和memcopy所做操作, 宿主类的方法任然存在, 只不过分类方法在宿主类方法之前, 在消息查找过程中, 根据选择器(selector)来查找, 一旦查到就返回, 由于分类方法在前, 故分类方法会优先实现, 从而会覆盖宿主类方法

2. 问:多个分类都有一个同名方法, 哪个生效?

答:后编译的生效

总结:


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

推荐阅读更多精彩内容