Objective-C之Category

来源:互联网 发布:龙泉驾校网络预约系统 编辑:程序博客网 时间:2024/05/17 22:09

1.categroy和extension

extension在编译期决议,它就是类的一部分,在编译期和头文件里的@interface以及实现文件里的@implement一起形成一个完整的类,它伴随类的产生而产生,亦随之一起消亡。extension一般用来隐藏类的私有信息,你必须有一个类的源码才能为一个类添加extension,所以你无法为系统的类比如NSString添加extension。但是category则完全不一样,它是在运行期决议的。就category和extension的区别来看,我们可以推导出一个明显的事实,extension可以添加实例变量,而category是无法添加实例变量的(因为在运行期,对象的内存布局已经确定,如果添加实例变量就会破坏类的内部布局,这对编译型语言来说是灾难性的)。**

2.categroy真面目

category在runtime层使用struct表示的,用结构体category_t表示
它包含了
1).类的名字(name)
2).类(cls)
3).category中所有给类添加的实例方法列表(instance_methods)
4).category中添加的类方法的列表(class_methods)
5).category实现的所有协议的列表(protocols)
6).category中添加的属性(properties)

typedef struct category_t {    const char *name;    struct class_t *cls;    struct method_list_t *instanceMethods;    struct method_list_t *classMethods;    struct protocol_list_t *protocols;    struct objc_property_list *instanceProperties;} category_t;

从category的结构定义能看出category可以添加实例方法,类方法,协议以及属性,不可以添加实例变量。
下面实现一个category看一看:
TextClass.h

#import <Foundation/Foundation.h>@interface TextClass : NSObject-(void)printFunction;@end@interface TextClass (Myaddition)@property(nonatomic,copy) NSString *string;-(void)printFunction;  //用来覆盖原来的方法@end

TextClass.m

#import "TextClass.h"@implementation TextClass-(void)printFunction{    NSLog(@"TextClass_print");}@end@implementation TextClass (Myaddition)-(void)printFunction{    NSLog(@"MyAddition_print");}@end

使用clang指令转换后看看会有些什么!(转换后出现了一个超级多代码的cpp文件,通过关键字搜索,找到如下关键代码)

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_TextClass_$_Myaddition __attribute__ ((used, section ("__DATA,__objc_const"))) = {sizeof(_objc_method),1,{{(struct objc_selector *)"printFunction", "v16@0:8", (void *)_I_TextClass_Myaddition_printFunction}}};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_TextClass_$_Myaddition __attribute__ ((used, section ("__DATA,__objc_const"))) = {sizeof(_prop_t),1,{{"string","T@\"NSString\",C,N"}}};extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_TextClass;static struct _category_t _OBJC_$_CATEGORY_TextClass_$_Myaddition __attribute__ ((used, section ("__DATA,__objc_const"))) = {"TextClass",0, // &OBJC_CLASS_$_TextClass,(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_TextClass_$_Myaddition,0,0,(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_TextClass_$_Myaddition,};static void OBJC_CATEGORY_SETUP_$_TextClass_$_Myaddition(void ) {_OBJC_$_CATEGORY_TextClass_$_Myaddition.cls = &OBJC_CLASS_$_TextClass;}#pragma section(".objc_inithooks$B", long, read, write)__declspec(allocate(".objc_inithooks$B")) static void *OBJC_CATEGORY_SETUP[] = {(void *)&OBJC_CATEGORY_SETUP_$_TextClass_$_Myaddition,};static struct _class_t *L_OBJC_LABEL_CLASS_$ [1] __attribute__((used, section ("__DATA, __objc_classlist,regular,no_dead_strip")))= {&OBJC_CLASS_$_TextClass,};static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= {&_OBJC_$_CATEGORY_TextClass_$_Myaddition,};static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

1.首先编译器生成了实例方法列表_OBJC_$_CATEGORY_INSTANCE_METHODS_TextClass_$_Myaddition和属性列表_OBJC_$_PROP_LIST_TextClass_$_Myaddition。两者的命名都遵循 公共前缀+类名+category名字 的方式,并且在实例方法列表中存放着我们在category里写的方法“printFunction”,属性列表里存放着我们在MyAddition里添加的属性“string”。还有就是category的名字用来给各种列表以及category本身结构体命名,而且有static修饰,所以在同一个编译单元内我们的category不能同名。

2.然后编译器生成了category本身_OBJC_$_CATEGORY_TextClass_$_Myaddition

3.最后,编译器在Data段下的_objc_catlist中生成了一个长为1的数组L_OBJC_LABEL_CATEGORY_$ [1],类型为static struct _category_t *,当然,如果有多个category则生成对应长度的数组,用于运行期category的加载。

3.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将map加载到内存,之后map_images中又会调用objc-runtime-new.mm文件中的_read_images初始化内存中的map,这个时候_read_images中包含了category的处理,在_read_images中我们找到Discover categr
最终会调用_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;            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" : "");                }            }            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数组,略去代码中无关的PrintConnection部分,这段代码大致如下:
1.判断category对应的类是否为空,如果为nil,则将整个这个类的category置nil。
2.如果这个category的实例方法,协议或者属性存在,并且这个类事实现,则重整类的数据。
3.把category的类方法和协议添加到类的metaclass里边。

在上述代码中,addUnattachedCategoryForClass方法只是把类和category做一个关联映射,真正去处理添加事宜的函数是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);    }}

从代码中可以看出remethodizeClass主要做下面几件事:
1.修改了类方法列表,协议列表,属性列表。
2.更新了类的方法缓存和子类的方法缓存。
而实现这些东西,又会去调用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);}

这个方法主要是通过while循环,遍历所有的category,也就是参数cats中的list属性,对于每一个category,得到它的方法列表mlist并存入mlists中。具体点就是取到方法列表,属性列表和协议列表,然后倒序插入到列表中,新生的category方法会优先于旧category的方法插入,然后将category的方法列表,属性列表和协议列表分别插入到类的方法列表的前面,生成新的数组。
换句话说,就是我们将所有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.主类中有多个数据集合的时候,使用realloc()函数将原来的空间扩展,然后把原来的数组复制到后面,最后再把新数组复制到前面。
2.主类中数据集合为空时,直接将指针指向新的数据集。
3.主类中只有一个数据集合的时候,使用malloc()重新申请一块内存,并将原来的集合放到最后面。
到这里,category的加载就完成了。
4.category为什么无法添加属性呢可以添加方法呢?
准确的说,category可以生成属性的声明,不会生成属性的实例变量,也没有getter和setter方法。
首先看一下类的结构(在runtime.h文件中可以找到):

struct objc_class {    Class isa  OBJC_ISA_AVAILABILITY;#if !__OBJC2__    Class super_class                         OBJC2_UNAVAILABLE;    const char *name                          OBJC2_UNAVAILABLE;    long version                              OBJC2_UNAVAILABLE;    long info                                 OBJC2_UNAVAILABLE;    long instance_size                        OBJC2_UNAVAILABLE;    struct objc_ivar_list *ivars              OBJC2_UNAVAILABLE;    struct objc_method_list **methodLists     OBJC2_UNAVAILABLE;    struct objc_cache *cache                  OBJC2_UNAVAILABLE;    struct objc_protocol_list *protocols      OBJC2_UNAVAILABLE;#endif} OBJC2_UNAVAILABLE;

从结构中可以看出,ivars是struct objc_ivar_list指针,methodLists是指向struct objc_method_list指针的指针,而且objc_class结构体大小是固定的,不可能往这个结构中添加数据,只能修改,所以ivars指向的是一个固定区域,只能修改成员变量值,不能增加成员变量个数。还有就是上述category的结构体category_t中没有实例变量存储单元。
methodList是一个二维数组,所以可以修改methodLists的值来增加成员方法,虽没办法扩展methodLists指向的内存区域,却可以改变这个内存区域的值(存储的是指针)。因此,可以动态添加方法,不能添加成员变量。

5.category方法覆盖

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

#import <Foundation/Foundation.h>#import "TextClass.h"#import <objc/runtime.h>int main(int argc, const char * argv[]) {    @autoreleasepool {        TextClass *myClass = [[TextClass alloc] init];        [myClass printFunction];  //将会调用categry中的方法        Class currentClass = [TextClass class];        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 ([@"printFunction" isEqualToString:methodName]) {                    lastImp = method_getImplementation(method);                    lastSel = method_getName(method);                }            }            typedef void (*fn)(id,SEL);            if (lastImp != NULL) {                fn f = (fn)lastImp;                f(myClass,lastSel); //将会调用原来类中的方法            }            free(methodList);        }    }    return 0;}//输出结果:2017-05-25 22:12:56.865 MyClass[2767:136261] MyAddition_print2017-05-25 22:12:56.866 MyClass[2767:136261] TextClass_printProgram ended with exit code: 0

6.为Category添加属性

正常情况下category中添加的属性是不会生成getter和setter方法的,那该如何解决呢?
可以通过运行时建立关联引用来解决!通过runtime库中如下两个函数来实现:

void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

这个方法可以实现运行时建立关联。其中有四个参数分别是:源对象,关联时的用来标记是哪一个属性的key(因为你可能会添加多个属性),关联的对象和关联策略。
关联关键字key是一个void类型的指针,每个关联的关键字必须是唯一的,一般用静态变量作为关键字。常用写法如下:

1static void *strKey = &strKey;2static NSString *strKey = @"strKey";3static char strKey;

关联策略policy是给属性添加属性关键字,是个枚举值:

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {    OBJC_ASSOCIATION_ASSIGN = 0,           /**< 指定对关联对象的弱引用. */    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< 指定对关联对象的强引用.*   并且不使用原子性. */    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< 指定复制的关联对象. *   并且不使用原子性. */    OBJC_ASSOCIATION_RETAIN = 01401,       /**< 指定对关联对象的强引用.*   并且是原子性的. */    OBJC_ASSOCIATION_COPY = 01403          /**< 指定复制的关联对象. *   并且是源子性的. */};
id objc_getAssociatedObject(id object, const void *key)

这个方法可以用来添加getter方法,两个参数分别为:objcet是源对象,key和上边setter的key要对应。
总体代码如下:
TextClass.h:

#import <Foundation/Foundation.h>@interface TextClass : NSObject-(void)printFunction;@end@interface TextClass (Myaddition)@property(nonatomic,copy) NSString *string;-(void)printFunction;@end

TextClass.m:

#import "TextClass.h"#import <objc/runtime.h>@implementation TextClass-(void)printFunction{    NSLog(@"TextClass_print");}@end@implementation TextClass (Myaddition)@dynamic string;static void *strKey = &strKey;-(void)setString:(NSString *)string{    objc_setAssociatedObject(self,&strKey,string,OBJC_ASSOCIATION_COPY);}-(NSString *)string{    return objc_getAssociatedObject(self, &strKey);}-(void)printFunction{    NSLog(@"MyAddition_print");}@end

main:

#import <Foundation/Foundation.h>#import "TextClass.h"#import <objc/runtime.h>int main(int argc, const char * argv[]) {    @autoreleasepool {        TextClass *myClass = [[TextClass alloc] init];        myClass.string = @"myString";        NSLog(@"%@",myClass.string);    }    return 0;}//输出结果:MyClass[1070:39010] myStringProgram ended with exit code: 0

这样就实现了给Category里添加属性!

原创粉丝点击