写博客只是为了让自己学的更深刻,参考:https://tech.meituan.com/DiveIntoCategory.html

分类(Category)是个啥玩意儿这里就不多介绍了,这里主要是研究下,分类的底层实现。

1. 分类中为什么不能添加成员变量?

在Objective-C提供的runtime函数中,确实有一个class_addIvar()函数用于给类添加成员变量,但是文档中特别说明:

This function may only be called after objc_allocateClassPair and before objc_registerClassPair. Adding an instance variable to an existing class is not supported.

意思是说,这个函数只能在“构建一个类的过程中”调用。一旦完成类定义,就不能再添加成员变量了。经过编译的类在程序启动后就runtime加载,没有机会调用addIvar。程序在运行时动态构建的类需要在调用 objc_allocateClassPair 之后,objc_registerClassPair之前才可以被使用,同样没有机会再添加成员变量。那为什么可以在类别中添加方法和属性呢?
因为方法和属性并不“属于”类实例,而成员变量“属于”类实例。我们所说的“类实例”概念,指的是一块内存区域,包含了isa指针和所有的成员变量。所以假如允许动态修改类成员变量布局,已经创建出的类实例就不符合类定义了,变成了无效对象。但方法定义是在objc_class中管理的,不管如何增删类方法,都不影响类实例的内存布局,已经创建出的类实例仍然可正常使用。

2. Category 和 Extension(类扩展)

Extension是Category的一个实例,被称为匿名分类,可以为一个类添加一些私有变量和方法。但是Extension和有名字的Category完全是两个东西。

Extension在编译期决定,它就是类的一部分,在编译期和头文件里的@interface和实现文件里的@implement一起形成一个完整的类,它伴随类的产生而产生,消亡而消亡。一般用来隐藏类的私有信息,你必须有一个类的源码才能添加Extension,比如 NSString 系统类就无法添加。

Category是在运行期决定的,无法添加成员变量,因为在运行期间,对象的内存布局已经确定,如果添加实例变量就会破坏类的内存布局。

3. Category 结构

所有的对象和类,在runtime层都是由struct表示的,category 也是如此,我们可以下载 runtime 的代码,objc-runtime-new.h 可以看到,category 使用 category_t 进行表示的:

typedef 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;     // 所有属性
} category_t;

 下面我新建了一个项目,给NSObject添加了一个分类:

@interface MyClass : NSObject

- (void)printName;

@end


@interface MyClass(MyAddition)

@property(nonatomic, copy) NSString *myName;

- (void)printName;

@end


@implementation MyClass(MyAddition)

- (void)printName{
    NSLog(@"MyAddition");
}

@end

@implementation MyClass

- (void)printName
{
    NSLog(@"MyClass");
}

@end

 然后使用 clang 命令 :clang -rewirte-objc MyClass.m,生成 .cpp 文件,打开查看,在文件的最下方:

// 首先生成了 _OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition 实例方法列表,和 _OBJC_$_PROP_LIST_MyClass_$_MyAddition 属性列表。遵循命名方法:公共前缀+类名+Category
注意:category的名字用来给各种列表以及后面的category结构体本身命名,而且有static来修饰,所以同一个编译单元(文件),不能有两个相同名字的category,否则会报编译错误。
  
static struct /*_method_list_t*/ {// 实例方法列表 unsigned int entsize; // sizeof(struct _objc_method) unsigned int method_count; struct _objc_method method_list[1]; } _OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition __attribute__ ((used, section ("__DATA,__objc_const"))) = { sizeof(_objc_method), 1, {{(struct objc_selector *)"printName", "v16@0:8", (void *)_I_MyClass_MyAddition_printName}} }; static struct /*_prop_list_t*/ { // 属性列表 unsigned int entsize; // sizeof(struct _prop_t) unsigned int count_of_properties; struct _prop_t prop_list[1]; } _OBJC_$_PROP_LIST_MyClass_$_MyAddition __attribute__ ((used, section ("__DATA,__objc_const"))) = { sizeof(_prop_t), 1, {{"myName","T@"NSString",C,N"}} }; extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_MyClass;
// 然后,生成了Category 本身, _OBJC_$_CATEGORY_MyClass_$_MyAddition ,并用上一步生成的 实例方法列表 和 属性列表 来初始化Category本身。
static struct _category_t _OBJC_$_CATEGORY_MyClass_$_MyAddition __attribute__ ((used, section ("__DATA,__objc_const"))) = { "MyClass", 0, // &OBJC_CLASS_$_MyClass, (const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition, 0, 0, (const struct _prop_list_t *)&_OBJC_$_PROP_LIST_MyClass_$_MyAddition, }; static void OBJC_CATEGORY_SETUP_$_MyClass_$_MyAddition(void ) { _OBJC_$_CATEGORY_MyClass_$_MyAddition.cls = &OBJC_CLASS_$_MyClass; } #pragma section(".objc_inithooks$B", long, read, write) __declspec(allocate(".objc_inithooks$B")) static void *OBJC_CATEGORY_SETUP[] = { (void *)&OBJC_CATEGORY_SETUP_$_MyClass_$_MyAddition, }; static struct _class_t *L_OBJC_LABEL_CLASS_$ [1] __attribute__((used, section ("__DATA, __objc_classlist,regular,no_dead_strip")))= { &OBJC_CLASS_$_MyClass, };
// 最终,编译器在DATA段下的 objc_catlistsection 里,保存了一个大小为1的 category_t 数组,里面那个就是我们刚才生成的Category,用于运行期Category的加载。 static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= { &_OBJC_$_CATEGORY_MyClass_$_MyAddition, }; static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

 编译期到此结束,下面我们看一下,是如何加载的。

4. Category 如何加载?

对于OC运行时,入口方法如下:objc-os.mm文件中

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    lock_init();
    exception_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);
}

 Category 被附加到类上是在 map_images 的时候发生的(我们可以点进去看到),_objc_init里面的调用的map_images最终会调用objc-runtime-new.mm里面的_read_images方法,而在_read_images方法的结尾,有以下的代码片段:

// Discover categories. 
    for (EACH_HEADER) {
     // 我们这里拿到的catlist 就是上面编译期间我们生成的category_t数组 category_t **catlist = _getObjc2CategoryList(hi, &count); bool hasClassProperties = hi->info()->hasCategoryClassProperties(); for (i = 0; i < count; i++) { category_t *cat = catlist[i]; Class cls = remapClass(cat->cls); if (!cls) { // Category's target class is missing (probably weak-linked). // Disavow any knowledge of this category. catlist[i] = nil; if (PrintConnecting) { _objc_inform("CLASS: IGNORING category ???(%s) %p with " "missing weak-linked target class", cat->name, cat); } continue; } // Process this category. // First, register the category with its target class. // Then, rebuild the class's method lists (etc) if // the class is realized. bool classExists = NO; if (cat->instanceMethods || cat->protocols || cat->instanceProperties) {
         // 获取到实例方法列表之后,下面这个方法只是将类和category进行一个关联 addUnattachedCategoryForClass(cat, cls, hi); if (cls->isRealized()) {
            // 最主要的实现代码是在这个方法中 remethodizeClass(cls); classExists = YES; } if (PrintConnecting) { _objc_inform("CLASS: found category -%s(%s) %s", cls->nameForLogging(), cat->name, classExists ? "on existing class" : ""); } } if (cat->classMethods || cat->protocols || (hasClassProperties && cat->_classProperties)) { addUnattachedCategoryForClass(cat, cls->ISA(), hi); if (cls->ISA()->isRealized()) { remethodizeClass(cls->ISA()); } if (PrintConnecting) { _objc_inform("CLASS: found category +%s(%s)", cls->nameForLogging(), cat->name); } } } }

略去PrintConnecting这个用于log的东西,这段代码很容易理解:
1)、把category的实例方法、协议以及属性添加到类上
2)、把category的类方法和协议添加到类的metaclass上

下面我们去探究下真正处理添加事宜的 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这个方法,我们去看下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_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);
}

 这个方法的主要任务是,获取所有该类所有的category,然后通过遍历,将所有category的属性,协议,方法分别放到一个大的数组里,然后通过 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;
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
            array()->count = newCount;
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            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)、category的方法没有“完全替换掉”原来类已经有的方法,也就是说如果category和原来类都有methodA,那么category附加完成之后,类的方法列表里会有两个methodA
2)、category的方法被放到了新方法列表的前面,而原来类的方法被放到了新方法列表的后面,这也就是我们平常所说的category的方法会“覆盖”掉原来类的同名方法,这是因为运行时在查找方法的时候是顺着方法列表的顺序查找的,它只要一找到对应名字的方法,就会罢休,殊不知后面可能还有一样名字的方法。

下面我们也会来验证一下:

5. 如何调用到被覆盖的主类的方法?

我们已经知道category其实并不是完全替换掉原来类的同名方法,只是category在方法列表的前面而已,所以我们只要顺着方法列表找到最后一个对应名字的方法,就可以调用原来类的方法:

 

Class currentClass = [MyClass class];
MyClass *my = [[MyClass alloc] init];

if (currentClass) {
    unsigned int methodCount;
    Method *methodList = class_copyMethodList(currentClass, &methodCount);
    IMP lastImp = NULL;
    SEL lastSel = NULL;
    for (NSInteger i = 0; i < methodCount; i++) {
        Method method = methodList[i];
        NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(method)) 
                                        encoding:NSUTF8StringEncoding];
        if ([@"printName" isEqualToString:methodName]) {
            lastImp = method_getImplementation(method);
            lastSel = method_getName(method);
        }
    }
    typedef void (*fn)(id,SEL);

    if (lastImp != NULL) {
        fn f = (fn)lastImp;
        f(my,lastSel);
    }
    free(methodList);
}

 6. 为分类添加属性,关联对象

如上所见,我们知道在category里面是无法为category添加实例变量的。但是我们很多时候需要在category中添加和对象关联的值,这个时候可以求助关联对象来实现。

- (void)setMyName:(NSString *)myName{
    objc_setAssociatedObject(self, @"myName", myName, OBJC_ASSOCIATION_COPY);
}

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

 这里就不多做介绍了,我们来看下,是如何关联的,去翻一下runtime的源码,在objc-references.mm文件中有个方法_object_set_associative_reference:

void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {
    // retain the new value (if any) outside the lock.
    ObjcAssociation old_association(0, nil);
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i != associations.end()) {
                // secondary table exists
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else {
                // create the new association (first time).
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects();
            }
        } else {
            // setting the association to nil breaks the association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i !=  associations.end()) {
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    refs->erase(j);
                }
            }
        }
    }
    // release the old value (outside of the lock).
    if (old_association.hasValue()) ReleaseValue()(old_association);
}

 我们可以看到,所有的关联对象都是由AssociationsManager 管理,而AssociationsManager的定义如下:

class AssociationsManager {
    // associative references: object pointer -> PtrPtrHashMap.
    static AssociationsHashMap *_map;
public:
    AssociationsManager()   { AssociationsManagerLock.lock(); }
    ~AssociationsManager()  { AssociationsManagerLock.unlock(); }
    
    AssociationsHashMap &associations() {
        if (_map == NULL)
            _map = new AssociationsHashMap();
        return *_map;
    }
};

AssociationsManager里面有一个静态的 AssociationHashMap 来存储所有的关联对象,这相当于把所有对象的关联对象都放到了一个map里,而map的key是对象的指针地址,而这个map的value又是另外一个 AssociationsHasMap, 里面保存的是关联对象的kv对。

在对象的销毁方法里面,见objc-runtime-new.mm:

void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj);
        // 这里判断是否有关联对象,有的话就去清理,所以不用自己去清理
        if (assoc) _object_remove_assocations(obj);
        obj->clearDeallocating();
    }

    return obj;
}

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!