分类-Category

分类-Category

分类的功能

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

分类的结构

const char *name;
    classref_t cls;
    WrappedPtr instanceMethods;
    WrappedPtr 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 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 

@implementation Test (Test1)

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

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

@end

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

你可能感兴趣的:(分类-Category)