Category笔记

为什么Category无法添加实例变量?

Category是无法添加实例变量的,当一个类被编译时,实例变量的布局也就形成了,如果Category在运行时添加实例变量就会破坏类的内存布局,这对编译型语言来说是灾难性的。
https://tech.meituan.com/DiveIntoCategory.html
http://yulingtianxia.com/blog/2014/11/05/objective-c-runtime/
https://stackoverflow.com/questions/39429512/objective-c-categories-doesnt-allow-to-add-instance-variables?noredirect=1&lq=1
https://stackoverflow.com/questions/39429512/objective-c-categories-doesnt-allow-to-add-instance-variables?noredirect=1&lq=1

为什么category里的方法会覆盖掉类里同名的方法

在运行时,category的方法被添加到类的方法列表里,并且会被添加到类原有的方法的前面。运行时在查找方法的时候是顺着方法列表的顺序查找的,它只要一找到对应名字的方法就会停止查找。

Category是如何给类添加方法的?

在运行时会把Category里的方法添加到类里。
在runtime的源码(我看的是objc4-723)objc-runtime-new.h里可以找到Category的定义:

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

自定义一个类:
MyClass.h

#import 

@interface MyClass : NSObject

- (void)printName;

@end

@interface MyClass(MyAddition)

@property(nonatomic, copy) NSString *name;

- (void)printName;

@end

MyClass.m:

#import "MyClass.h"

@implementation MyClass

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

@end

@implementation MyClass(MyAddition)

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

@end

我们使用clang的命令去看看category到底会变成什么:

clang -rewrite-objc MyClass.m

然后打开得到的MyClass.cpp文件,在文件最后可以找到下面的代码:

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 /*_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,
    {{"name","T@\"NSString\",C,N"}}
};

//生成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 struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= {
    &_OBJC_$_CATEGORY_MyClass_$_MyAddition,
};
  • 编译器会先生成实例方法列表_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition和属性列表_OBJC_$_PROP_LIST_MyClass_$_MyAddition __attribute__。而且实例方法列表里面填充的正是我们在MyAddition这个Category里面写的方法printName,而属性列表里面填充的也正是我们在MyAddition里添加的name属性;
  • 之后,编译器会生成Category本身_OBJC_$_CATEGORY_MyClass_$_MyAddition,并且使用上面已经生成的实例方法列表和属性列表来初始化;
  • 最后,编译器在DATA段下的objc_catlist section里保存了一个大小为1的Category_t的数组L_OBJC_LABELCATEGORY$(当然,如果有多个Category,会生成对应长度的数组),用于运行期Category的加载。

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

/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/

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的时候发生的,在new-ABI的标准下,_objc_init里面的调用的map_images最终会调用objc-runtime-new.mm里面的_read_images方法,而在_read_images方法的结尾,有以下的代码片段:

// Discover categories. 
    for (EACH_HEADER) {
        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;

            //把category的实例方法、协议以及属性添加到类上
            if (cat->instanceMethods ||  cat->protocols  
                ||  cat->instanceProperties) 
            {
                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" : "");
                }
            }

            //把category的类方法、协议以及类属性添加到元类上
            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);
                }
            }
        }
    }

首先,我们拿到的catlist就是上节中讲到的编译器为我们准备的category_t数组,之后做了两件事:

  • 把category的实例方法、协议以及属性添加到类上;
  • 把category的类方法、协议以及类属性添加到元类上。

addUnattachedCategoryForClass只是把类和category做一个关联映射,而remethodizeClass才是真正去处理添加事宜的函数:


/***********************************************************************
* remethodizeClass
* Attach outstanding categories to an existing class.
* Fixes up cls's method list, protocol list, and property list.
* Updates method caches for cls and its subclasses.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
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

// 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, 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];
        //将所有的category的实例方法列表放到mlists列表中
        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            mlists[mcount++] = mlist;
            fromBundle |= entry.hi->isBundle();
        }
       
        //将所有的category的属性列表放到proplists列表中
        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            proplists[propcount++] = proplist;
        }

        //将所有的category的协议列表放到protolists列表中
        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);
}

attachCategories做的工作相对比较简单,它只是把所有category的实例方法列表拼成了一个大的实例方法列表,然后转交给了attachLists函数,attachLists函数在objc-runtime-new.h中:

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

从上面的memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0])); }可以看出,category的方法会被添加到类原有的方法的前面。如果category和原来类都有methodA,那么category附加完成之后,类的方法列表里会有两个methodA这也就是我们平常所说的category的方法会“覆盖”掉原来类的同名方法的原因。这是因为运行时在查找方法的时候是顺着方法列表的顺序查找的,它只要一找到对应名字的方法就会停止查找。

类的多个类别有相同方法名

如果类或类别实现了+load方法,当类或类别被加入到OC的runtime时,会调用类或类别实现的+load方法,并且类的load方法在类别的load方法之前调用。如果有多个类别实现了+load方法,则多个类别里的+load方法的调用顺序是由compile sources里的文件顺序决定的,在compile sources里后面的category文件会先调用+load方法。

类和类别里其他的同名方法在调用时,类别里的方法会取代类里的方法(原因之前有提到),多个类别里的同名方法会调用哪一个也是由compile sources里的category文件顺序决定的。

如果类别里有和类同名的方法,会调用类别里的方法,如果一个类有多个类别且每个类别里都有同名的方法,那么调用那个方法是由build phase里的顺序决定的。在build phase里后编译的category,在运行时里category的方法会被添加到类的方法列表里前面的位置。
我们的代码里有MyClass和MyClass的两个category (Category1和Category2),MyClass和两个category都添加了+load方法,并且Category1和Category2都写了MyClass的printName方法:

在Xcode中点击Edit Scheme,添加如下两个环境变量(可以在执行load方法以及加载category的时候打印log信息,更多的环境变量选项可参见objc-private.h):


此时的complie sources里的顺序是这样的:



运行项目,我们会看到控制台打印很多东西出来,我们只找到我们想要的信息,顺序如下:

objc[63746]: REPLACED: -[MyClass printName]  by category Category1
objc[63746]: REPLACED: -[MyClass printName]  by category Category2  
···
···
···
objc[64365]: LOAD: class 'MyClass' scheduled for +load
objc[64365]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[64365]: LOAD: category 'MyClass(Category2)' scheduled for +load

objc[63746]: LOAD: +[MyClass load]
objc[63746]: LOAD: +[MyClass(Category1) load]
objc[63746]: LOAD: +[MyClass(Category2) load]

可以看出,类的printName方法会被Category2里的printName取代;+load方法的调用顺序是先调用类里的load方法,然后类别里的load方法的调用顺序和编译顺序是一致的。并且category的方法添加到类里的工作实现与load方法调用的,因此可以在load方法里调用
换一下complie sources里的顺序:


objc[63746]: REPLACED: -[MyClass printName]  by category Category2
objc[63746]: REPLACED: -[MyClass printName]  by category Category1 
···
···
···
objc[64433]: LOAD: class 'MyClass' scheduled for +load
objc[64433]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[64433]: LOAD: category 'MyClass(Category1)' scheduled for +load

objc[64433]: LOAD: +[MyClass load]
objc[64433]: LOAD: +[MyClass(Category2) load]
objc[64433]: LOAD: +[MyClass(Category1) load]

此时category1里的printName会最终取代类里的printName。

通过关联对象的方法添加属性

Category里可以添加属性,但只会添加setter和getter方法的声明,不会添加setter和getter方法的实现和实例变量,
我们可以通过 Associated Objects 来弥补不能添加实例变量这一不足。
相关函数:

/** 
 * Sets an associated value for a given object using a given key and association policy.
 * 
 * @param object The source object for the association.
 * @param key The key for the association.
 * @param value The value to associate with the key key for object. Pass nil to clear an existing association.
 * @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
 * 
 */
OBJC_EXPORT void
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
                         id _Nullable value, objc_AssociationPolicy policy)

/** 
 * Returns the value associated with a given object for a given key.
 * 
 * @param object The source object for the association.
 * @param key The key for the association.
 * 
 * @return The value associated with the key \e key for \e object.
 */
OBJC_EXPORT id _Nullable
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
  • objc_setAssociatedObject 用于给对象添加关联对象,传入 nil 则可以移除已有的关联对象;
  • objc_getAssociatedObject 用于获取关联对象;

这两个方法都要传入一个key值,这个 key 值必须保证是一个对象级别(的唯一常量。一般来说,有以下三种推荐的 key 值:

  • 声明 static char kAssociatedObjectKey; ,使用 &kAssociatedObjectKey 作为 key 值;
  • 声明 static void *kAssociatedObjectKey = &kAssociatedObjectKey; ,使用 kAssociatedObjectKey 作为 key 值;
  • 用selector ,使用 getter 方法的名称作为 key 值。
@interface MyClass (Category1)
@property (nonatomic, copy) NSString *name;
@end

#import "MyClass+Category1.h"
#import 
@implementation MyClass (Category1)

- (void)setName:(NSString *)name{
    objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY);
}

- (NSString *)name{
    return objc_getAssociatedObject(self, _cmd);
}

@end
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

如果使用OBJC_ASSOCIATION_ASSIGN,当对象的关联对象释放了,调用objc_getAssociatedObject()会崩溃。因为objc_setAssociatedObject ()存储的是关联对象的地址,虽然关联对象释放了,但是对象存储的关联对象的地址并没有被移除,此时调用objc_getAssociatedObject()会崩溃。所以我们在使用弱引用的关联对象时要非常小心。

关联对象存在什么地方呢? 如何存储? 对象销毁时候如何处理关联对象呢?
所有的关联对象都是由一个类AssociationsManager管理的,AssociationsManager里面是有一个静态的AssociationsHashMap来存储所有的关联对象的。AssociationsHashMap的key是对象的指针地址,value是ObjectAssociationMapObjectAssociationMap也是一个哈希表,里面存放了以key为指针地址的对象的所有的关联对象的key-value。
一个对象的所有关联对象是在这个对象被释放时调用的 _object_remove_assocations 函数中被移除的。
http://blog.leichunfeng.com/blog/2015/06/26/objective-c-associated-objects-implementation-principle/

你可能感兴趣的:(Category笔记)