类的加载原理下

上篇文章讲了类是如何加载的,但是我们只看到了类里面的方法,属性和协议的加载,并没有看到分类加载,这篇文章介绍分类的加载。

分类加载

1. 分类的本质

首先我们通过一个简单代码然后clang看一下cpp文件里代码

@interface NSObject (HFA)

@end

@implementation NSObject (HFA)

+ (void)load {
    NSLog(@"HFA:%s", __FUNCTION__);
}
@end

int main(int argc, char * argv[]) {
    NSString * appDelegateClassName;
    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
    }
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}

通过clang后我们看到这么一个结构体:

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

static struct _category_t _OBJC_$_CATEGORY_NSObject_$_HFA __attribute__ ((used, section ("__DATA,__objc_const"))) = 
{
    "NSObject",  // 这边是分类的名称,正常应该是HFA,但是却变成了NSObject,主要是因为目前是编译状态,我们的分类是在运行时被加载到类里面的,也是在那个时候才确定分类名称
    0, // &OBJC_CLASS_$_NSObject,
    0,
    (const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_NSObject_$_HFA,
    0,
    0,
};

name:分类名称
cls:对应的类
instance_methods:实例方法列表
class_methods:类方法列表
protocols:协议
properties:属性
似乎类的信息该有的都有了,但是仔细一看少了成员变量,这就是为什么分类不能添加成员变量的原因。
总之分类呢本质也是一个结构体。

2. 分类加载的代码是哪里?

首先我们要先知道分类是在哪里被加载进来的?
我们添加了一个分类代码如下:

@implementation HFObject (HFA)

- (void)say666 {
    NSLog(@"%s", __FUNCTION__);
}

- (void)say111 {
    NSLog(@"%s", __FUNCTION__);
}

- (void)say222 {
    NSLog(@"%s", __FUNCTION__);
}

+ (void)load {
    NSLog(@"HFA:%s", __FUNCTION__);
}
@end

目前我们的分类有load的方法,主类也有load方法,然后继续上编文章的代码追踪

static void methodizeClass(Class cls, Class previously)
{
    runtimeLock.assertLocked();

    bool isMeta = cls->isMetaClass();
    auto rw = cls->data();
    auto ro = rw->ro();
    auto rwe = rw->ext();
    
    const char *mangledName = cls->nonlazyMangledName();
    if (strcmp(mangledName, "HFObject") == 0 && !isMeta) {
        auto ro = (class_ro_t *)cls->data();
        printf("需要研究的类----%s\n", __FUNCTION__);
    }

    // Methodizing for the first time
    if (PrintConnecting) {
        _objc_inform("CLASS: methodizing class '%s' %s", 
                     cls->nameForLogging(), isMeta ? "(meta)" : "");
    }

    // Install methods and properties that the class implements itself.
    method_list_t *list = ro->baseMethods();
    if (list) {
        prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls), nullptr);
        if (rwe)
            rwe->methods.attachLists(&list, 1);
    }

    property_list_t *proplist = ro->baseProperties;
    if (rwe && proplist) {
        rwe->properties.attachLists(&proplist, 1);
    }

    protocol_list_t *protolist = ro->baseProtocols;
    if (rwe && protolist) {
        rwe->protocols.attachLists(&protolist, 1);
    }

    // Root classes get bonus method implementations if they don't have 
    // them already. These apply before category replacements.
    if (cls->isRootMetaclass()) {
        // root metaclass
        addMethod(cls, @selector(initialize), (IMP)&objc_noop_imp, "", NO);
    }

    // Attach categories.
    if (previously) {
        if (isMeta) {
            objc::unattachedCategories.attachToClass(cls, previously,
                                                     ATTACH_METACLASS);
        } else {
            // When a class relocates, categories with class methods
            // may be registered on the class itself rather than on
            // the metaclass. Tell attachToClass to look for those.
            objc::unattachedCategories.attachToClass(cls, previously,
                                                     ATTACH_CLASS_AND_METACLASS);
        }
    }
    objc::unattachedCategories.attachToClass(cls, cls,
                                             isMeta ? ATTACH_METACLASS : ATTACH_CLASS);
}

通过上面代码我们知道主类在这边对方法进行了排序,初始化属性和协议,而在代码最后面objc::unattachedCategories.attachToClass(cls, cls, isMeta ? ATTACH_METACLASS : ATTACH_CLASS);这边似乎就是对分类的加载。因此我们来到attachToClass方法


void attachToClass(Class cls, Class previously, int flags)
    {
        runtimeLock.assertLocked();
        ASSERT((flags & ATTACH_CLASS) ||
               (flags & ATTACH_METACLASS) ||
               (flags & ATTACH_CLASS_AND_METACLASS));
        
        const char *mangledName = cls->nonlazyMangledName();
        if (strcmp(mangledName, "HFObject") == 0) {
            auto ro = (class_ro_t *)cls->data();
            printf("需要研究的类----%s\n", __FUNCTION__);
        }
        auto &map = get();
        auto it = map.find(previously);

        if (it != map.end()) {
            category_list &list = it->second;
            if (flags & ATTACH_CLASS_AND_METACLASS) {
                int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
                attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);
                attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);
            } else {
                attachCategories(cls, list.array(), list.count(), flags);
            }
            map.erase(it);
        }
    }

在这个方法里面我们似乎是找到了分类加载的方法attachCategories,继续来看看attachCategories代码

// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order, 
// oldest categories first.
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
                 int flags)
{
    if (slowpath(PrintReplacedMethods)) {
        printReplacements(cls, cats_list, cats_count);
    }
    if (slowpath(PrintConnecting)) {
        _objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
                     cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
                     cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
    }

    /*
     * Only a few classes have more than 64 categories during launch.
     * This uses a little stack, and avoids malloc.
     *
     * Categories must be added in the proper order, which is back
     * to front. To do that with the chunking, we iterate cats_list
     * from front to back, build up the local buffers backwards,
     * and call attachLists on the chunks. attachLists prepends the
     * lists, so the final result is in the expected order.
     */
    constexpr uint32_t ATTACH_BUFSIZ = 64;
    method_list_t   *mlists[ATTACH_BUFSIZ];
    property_list_t *proplists[ATTACH_BUFSIZ];
    protocol_list_t *protolists[ATTACH_BUFSIZ];

    uint32_t mcount = 0;
    uint32_t propcount = 0;
    uint32_t protocount = 0;
    bool fromBundle = NO;
    bool isMeta = (flags & ATTACH_METACLASS);
    auto rwe = cls->data()->extAllocIfNeeded();
    const char *mangledName = cls->nonlazyMangledName();
    if (strcmp(mangledName, "HFObject") == 0 && !isMeta) {
        printf("需要研究的类----%s\n", __FUNCTION__);
    }
    for (uint32_t i = 0; i < cats_count; i++) {
        auto& entry = cats_list[I];

        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            if (mcount == ATTACH_BUFSIZ) {
                prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
                rwe->methods.attachLists(mlists, mcount);
                mcount = 0;
            }
            mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        property_list_t *proplist =
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            if (propcount == ATTACH_BUFSIZ) {
                rwe->properties.attachLists(proplists, propcount);
                propcount = 0;
            }
            proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
        if (protolist) {
            if (protocount == ATTACH_BUFSIZ) {
                rwe->protocols.attachLists(protolists, protocount);
                protocount = 0;
            }
            protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
        }
    }

    if (mcount > 0) {
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }

    rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);

    rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}

image.png

当我们断点来到这边然后通过lldb调试查看entry.cat内容
image.png

在这边获取到了分类信息,并将分类挂载到数组mlists
注意:auto rwe = cls->data()->extAllocIfNeeded(); 这边获取了rwe,还记得在上篇文章中我们说过将需要动态更新的部分提取出来存入class_rw_ext_trwe,而分类就是动态更新。

if (mcount > 0) {
        prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
                           NO, fromBundle, __func__);
        rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
        if (flags & ATTACH_EXISTING) {
            flushCaches(cls, __func__, [](Class c){
                // constant caches have been dealt with in prepareMethodLists
                // if the class still is constant here, it's fine to keep
                return !c->cache.isConstantOptimizedCache();
            });
        }
    }

这边即是将分类的方法进行了排序,然后添加到类里面。
这边又是如何添加到类里面呢?

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;
            array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
            newArray->count = newCount;
            array()->count = newCount;

            for (int i = oldCount - 1; i >= 0; I--)
                newArray->lists[i + addedCount] = array()->lists[I];
            for (unsigned i = 0; i < addedCount; I++)
                newArray->lists[i] = addedLists[I];
            free(array());
            setArray(newArray);
            validate();
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
            validate();
        } 
        else {
            // 1 list -> many lists
            Ptr<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;
            for (unsigned i = 0; i < addedCount; I++)
                array()->lists[i] = addedLists[I];
            validate();
        }
    }

首先我们来解读一下这块代码:
array()二维数组存在,即hasArray()为true,则是新创建了一个了newArray,然后原来的方法添加到后面,新的方法添加到前面。
list为空且指添加一个方法列表,直接list指向该方法列表,当前是一维数组
当二维数组array为空,且list不为空,创建一个二维数组array,将list添加到末尾,新的数组添加到前面
总的来说如果没有分类就是一个一维数组,如果有分类,会创建一个二维数组,将主类的方法列表放在末尾,分类的方法列表放在前面,当objc_msgSend 发送消息调用方法时,找到了主类方法后会一直往前查找是否还有同名方法,其实就是查找分类方法,所以我们的分类方法会优先调用
上面已经证实了分类方法加载代码位置,接下来我们来分析什么时候调用

分类什么时候进行加载

目前我们已经确定分类加载是attachCategories函数,接下来我们可以看看都有哪些调用

  1. read_image->realizeClassWithoutSwift->methodizeClass->attachToClass->attachCategories
  2. load_images->loadAllCategories->load_categories_nolock->attachCategories
    我们通过断点调试
    image.png

    发现走的是线路2,为什么走线路2呢?猜测应该是load_images要调用某个类的load方法,调用前先将该类初始化把方法都加载进来
    目前先放一放,我们研究一下几种情况

  1. 主类和分类都有load方法
    这种情况我们在上面已经分析过了,走的流程
    read_image->realizeClassWithoutSwift->methodizeClass->attachToClass
    load_images->loadAllCategories->load_categories_nolock->attachCategories
  2. 主类有load方法,分类没有
    read_image->realizeClassWithoutSwift->methodizeClass->attachToClass
  3. 主类没有load方法,分类有
    read_image->realizeClassWithoutSwift->methodizeClass->attachToClass
  4. 主类没有load方法,多个分类里面有load方法
    read_image->realizeClassWithoutSwift->methodizeClass->attachToClass->attachCategories
    现在就清晰的知道了线路1和线路2都是在什么情况走的了
    现在还有一点就是2和3里面的分类是什么时候加载的呢?
    首先我们先看看2:主类有load方法,分类没有
    我们知道有load方法就是非懒加载类,就会来到realizeClassWithoutSwift方法
    去加载ro和rw,这时候我们来看看加载完后的ro
    image.png

    image.png

    lldb调试就可以知道,ro里面已经加载了分类的方法了,也就是说从mach-o里面把类方法和分类方法都加载进来了
    同样的3:主类没有load方法,分类有也是如此。

这边我们可以得出一个小小的结论:一个类的load方法越多会程序的启动时间越长,所以平时我们开发的时候除非必要,否则尽量少写load方法来影响程序启动。

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