分类-Category

分类-Category

分类的功能

在OC中,我们可以使用分类为类添加方法,属性.也可以覆盖类原有的方法,自己添加新的实现.(说是覆盖,其实不然.在稍后分类加载时间会解释原因)

分类的结构

const char *name;
    classref_t cls;
    WrappedPtr<method_list_t, PtrauthStrip> instanceMethods;
    WrappedPtr<method_list_t, PtrauthStrip> 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);
    
    protocol_list_t *protocolsForMeta(bool isMeta) {
        if (isMeta) return nullptr;
        else return protocols;
    }
};

从源码可以看出,分类是名为 category_t 的结构体类型数据.

category_t的成员

  • instanceMethods:实例方法
  • classMethods:类方法
  • protocols:协议
  • instanceProperties:实例属性
  • _classProperties:类属性

分类的加载顺序

分析iOS App启动时的一系列方法,可以看到分类的加载规则.下面是一系列经过的方法

_objc_init ==> map_images ==> map_images_nolock ==> _read_images ==> remethodizeClass ==> attachCategories

_read_images

// Discover classes. Fix up unresolved future classes. Mark bundle classes.

    for (EACH_HEADER) {
        if (! mustReadClasses(hi)) {
            // Image is sufficiently optimized that we need not call readClass()
            continue;
        }

        bool headerIsBundle = hi->isBundle();
        bool headerIsPreoptimized = hi->isPreoptimized();

        classref_t *classlist = _getObjc2ClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = (Class)classlist[i];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);

            if (newCls != cls  &&  newCls) {
                // Class was moved but not deleted. Currently this occurs 
                // only when the new class resolved a future class.
                // Non-lazily realize the class below.
                resolvedFutureClasses = (Class *)
                    realloc(resolvedFutureClasses, 
                            (resolvedFutureClassCount+1) * sizeof(Class));
                resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
            }
        }
    }
 // Discover protocols. Fix up protocol refs.
    for (EACH_HEADER) {
        extern objc_class OBJC_CLASS_$_Protocol;
        Class cls = (Class)&OBJC_CLASS_$_Protocol;
        assert(cls);
        NXMapTable *protocol_map = protocols();
        bool isPreoptimized = hi->isPreoptimized();
        bool isBundle = hi->isBundle();

        protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map, 
                         isPreoptimized, isBundle);
        }
    }
 // Discover categories. Only do this after the initial category
    // attachment has been done. For categories present at startup,
    // discovery is deferred until the first load_images call after
    // the call to _dyld_objc_notify_register completes. rdar://problem/53119145
    if (didInitialAttachCategories) {
        for (EACH_HEADER) {
            load_categories_nolock(hi);
        }
    }
    
    // Realize non-lazy classes (for +load methods and static instances)
    for (EACH_HEADER) {
        classref_t const *classlist = hi->nlclslist(&count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;

            addClassTableEntry(cls);

            if (cls->isSwiftStable()) {
                if (cls->swiftMetadataInitializer()) {
                    _objc_fatal("Swift class %s with a metadata initializer "
                                "is not allowed to be non-lazy",
                                cls->nameForLogging());
                }
                // fixme also disallow relocatable classes
                // We can't disallow all Swift classes because of
                // classes like Swift.__EmptyArrayStorage
            }
            realizeClassWithoutSwift(cls, nil);
        }
    }

从_read_images方法中,我摘抄了部分代码.从这一部分代码,我们可以看到类的加载顺序.

  • Discover classes. Fix up unresolved future classes. Mark bundle classes.

  • Discover protocols. Fix up protocol refs.

  • Discover categories.===> load_categories_nolock但是很明显.这里有一个个判断值didInitialAttachCategories.通过源码看到.这个值一开始为false.所以这时并未加载分类.

  • 继续往下走.会发现有一种情况.就是non-lazy classes会调用realizeClassWithoutSwift方法,方法内部会调用methodizeClass在内部使用objc::unattachedCategories.attachToClass 将分类与类连接上.
    void
    load_images(const char *path __unused, const struct mach_header *mh)
    {
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
    didInitialAttachCategories = true;
    loadAllCategories();
    }

       // Return without taking locks if there are no +load methods here.
       if (!hasLoadMethods((const headerType *)mh)) return;
    
       recursive_mutex_locker_t lock(loadMethodLock);
    
       // Discover load methods
       {
           mutex_locker_t lock2(runtimeLock);
           prepare_load_methods((const headerType *)mh);
       }
    
       // Call +load methods (without runtimeLock - re-entrant)
       call_load_methods();
    

    }

    static void loadAllCategories() {
    mutex_locker_t lock(runtimeLock);

       for (auto *hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
           load_categories_nolock(hi);
       }
    

    }

load_categories_nolock

static void load_categories_nolock(header_info *hi) {
    bool hasClassProperties = hi->info()->hasCategoryClassProperties();

    size_t count;
    auto processCatlist = [&](category_t * const *catlist) {
        for (unsigned i = 0; i < count; i++) {
            category_t *cat = catlist[i];
            Class cls = remapClass(cat->cls);
            locstamped_category_t lc{cat, hi};
            // First, register the category with its target class.
            // Then, rebuild the class's method lists (etc) if
            // the class is realized.
            if (cat->instanceMethods ||  cat->protocols
                ||  cat->instanceProperties)
            {
                if (cls->isRealized()) {
                    attachCategories(cls, &lc, 1, ATTACH_EXISTING);
                } else {
                    objc::unattachedCategories.addForClass(lc, cls);
                }
            }

            if (cat->classMethods  ||  cat->protocols
                ||  (hasClassProperties && cat->_classProperties))
            {
                if (cls->ISA()->isRealized()) {
                    attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
                } else {
                    objc::unattachedCategories.addForClass(lc, cls->ISA());
                }
            }
        }
    };
    processCatlist(_getObjc2CategoryList(hi, &count));
    processCatlist(_getObjc2CategoryList2(hi, &count));
}

从load_categories_nolock方法中摘抄了部分代码,发现内部调用了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();

    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);
}
  • method_list_t *mlists(方法数组)
  • property_list_t *proplists(属性数组)
  • protocol_list_t *protolists(协议数组)

可以看到.在attachCategories方法中.会加载方法,属性,协议.并且.从load_categories_nolock方法中可以看出.先加载实例方法,再加载类方法.也就是说.是先处理类对象,再处理元类对象.

在attachCategories 中遍历加载的分类列表.将每一个分类中方法,属性,协议通过attachLists方法.将三个数组拼接到类对象或者元类对象的对应的 方法,属性,协议 列表中.

从attachToClass看分类加载时机

从源码可以看出.加载分类的时候.都会调用objc::unattachedCategories.attachToClass.我添加了自己的Test类做比较.在attachToClass中增加了自己的代码并添加断点.查看调用栈

  • 1.Test类与分类皆实现了+load方法

  • 2.Test类实现+load方法,Test的分类没有实现+load方法

  • 3.Test类没有实现+load方法,Test的分类实现+load方法

  • 4.Test类没实现+load方法,Test的分类也没有实现+load方法

情况1,2结果:
image-20210518162747394.png

情况3结果:
image-20210518162840934.png

情况4结果:
image-20210518162909336.png

可以看出.只要一个类实现了+load的方法.类就会强制在read_images时进行分类加载.

而类不实现+load,分类实现了,则会在load_images方法进行分类加载

而类与分类都不实现的情况下.则会在调用方法时,进行类的加载.msgSend ===> lookUpImpOrForward

attachLists

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

从attachLists中可以看出.在扩容方法数组时,会将类的旧方法往后移,然后通过for循环将分类的方法填充进空出的位置中.所以,如果分类有跟本类同名方法,并不会覆盖原有方法.只是分类方法在方法列表中排前,所以msgSend过程中.会先被命中.

并且多个分类有同名方法时,加载顺序是怎么样呢?

@interface Test : NSObject
@end

@implementation Test
@end

@interface Test (Test1)
+ (void)test;
@end

@implementation Test (Test1)
+ (void)test {
    NSLog(@"%s",__func__);
}
@end

@interface Test (Test2)
+ (void)test;
@end

@implementation Test (Test2)
+ (void)test {
    NSLog(@"%s",__func__);
}
@end
image-20210518164916835.png

build phases中,在调换Test1,Test2的顺序后.打印出的结果也不痛.

//当Test1在上
TestExtension[60879:1094130] +[Test(Test2) test]
//Test2在上
TestExtension[60935:1095749] +[Test(Test1) test]

分类添加属性

上面看到.虽然category_t中有属性列表,并无成员列表.
所以为类添加属性后,由于不存在成员列表.所以也不会像类声明属性时,默认会有@synthesize xxxx这一步骤.生成getter,setter方法和成员名成员标量.

所以当我们直接使用分类声明的属性时,无论是取值还是赋值.都会报对应的 unrecognized selector sent to instance错误.

那么,我们想要通过分类,为类添加属性,应该怎么做呢?

我们可以通过OC的关联对象来完成分类为类添加属性的功能.

关联对象

runtime中,关联对象允许我们动态的把一个对象与某一块地址动态的关联起来.篇幅太长,这里不做原理的分析.只简单写一下怎么完成关联对象

//Test+Test1.h
#import "Test.h"

NS_ASSUME_NONNULL_BEGIN

@interface Test (Test1)

@property(nonatomic, copy)NSString *testName;

@end

NS_ASSUME_NONNULL_END

//Test+Test1.m
#import "Test+Test1.h"
#import <objc/runtime.h>

@implementation Test (Test1)

- (void)setTestName:(NSString *)testName {
    objc_setAssociatedObject(self, "testName", testName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)testName {
    return objc_getAssociatedObject(self, "testName");
}

@end

上述就是使用关联对象,完成分类为类添加属性的示例.

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

推荐阅读更多精彩内容