深入理解Objective-C:Category(上)

来源:互联网 发布:webgl编程指南 pdf 编辑:程序博客网 时间:2024/05/21 10:02

来源: 美团开发团队   

链接:http://tech.meituan.com/DiveIntoCategory.html


摘要


无论一个类设计的多么完美,在未来的需求演进中,都有可能会碰到一些无法预测的情况。那怎么扩展已有的类呢?一般而言,继承和组合是不错的选择。但是在Objective-C 2.0中,又提供了category这个语言特性,可以动态地为已有类添加新行为。如今category已经遍布于Objective-C代码的各个角落,从Apple官方的framework到各个开源框架,从功能繁复的大型APP到简单的应用,catagory无处不在。本文对category做了比较全面的整理,希望对读者有所裨益。


简介


本文作者来自美团酒店旅游事业群iOS研发组。我们致力于创造价值、提升效率、追求卓越。欢迎大家加入我们(简历请发送到邮箱majia03@meituan.com)。

本文系学习Objective-C的runtime源码时整理所成,主要剖析了category在runtime层的实现原理以及和category相关的方方面面,内容包括:


  • 初入宝地-category简介

  • 连类比事-category和extension

  • 挑灯细览-category真面目

  • 追本溯源-category如何加载

  • 旁枝末叶-category和+load方法

  • 触类旁通-category和方法覆盖

  • 更上一层-category和关联对象


1、初入宝地-category简介


category是Objective-C 2.0之后添加的语言特性,category的主要作用是为已经存在的类添加方法。除此之外,apple还推荐了category的另外两个使用场景1


  • 可以把类的实现分开在几个不同的文件里面。这样做有几个显而易见的好处,a)可以减少单个文件的体积 b)可以把不同的功能组织到不同的category里 c)可以由多个开发者共同完成一个类 d)可以按需加载想要的category 等等。

  • 声明私有方法


不过除了apple推荐的使用场景,广大开发者脑洞大开,还衍生出了category的其他几个使用场景:


  • 模拟多继承

  • 把framework的私有方法公开


Objective-C的这个语言特性对于纯动态语言来说可能不算什么,比如javascript,你可以随时为一个“类”或者对象添加任意方法和实例变量。但是对于不是那么“动态”的语言而言,这确实是一个了不起的特性。


2、连类比事-category和extension


extension看起来很像一个匿名的category,但是extension和有名字的category几乎完全是两个东西。 extension在编译期决议,它就是类的一部分,在编译期和头文件里的@interface以及实现文件里的@implement一起形成一个完整的类,它伴随类的产生而产生,亦随之一起消亡。extension一般用来隐藏类的私有信息,你必须有一个类的源码才能为一个类添加extension,所以你无法为系统的类比如NSString添加extension。(详见2)


但是category则完全不一样,它是在运行期决议的。

就category和extension的区别来看,我们可以推导出一个明显的事实,extension可以添加实例变量,而category是无法添加实例变量的(因为在运行期,对象的内存布局已经确定,如果添加实例变量就会破坏类的内部布局,这对编译型语言来说是灾难性的)。


3、挑灯细览-category真面目


我们知道,所有的OC类和对象,在runtime层都是用struct表示的,category也不例外,在runtime层,category用结构体category_t(在objc-runtime-new.h中可以找到此定义),它包含了


1)、类的名字(name)

2)、类(cls)

3)、category中所有给类添加的实例方法的列表(instanceMethods)

4)、category中所有添加的类方法的列表(classMethods)

5)、category实现的所有协议的列表(protocols)

6)、category中添加的所有属性(instanceProperties)


typedefstructcategory_t{

    constchar *name;

    classref_tcls;

    structmethod_list_t *instanceMethods;

    structmethod_list_t *classMethods;

    structprotocol_list_t *protocols;

    structproperty_list_t *instanceProperties;

}category_t;


从category的定义也可以看出category的可为(可以添加实例方法,类方法,甚至可以实现协议,添加属性)和不可为(无法添加实例变量)。

ok,我们先去写一个category看一下category到底为何物:


MyClass.h:


#import <Foundation/Foundation.h>

 

@interfaceMyClass : NSObject

 

-(void)printName;

 

@end

 

@interfaceMyClass(MyAddition)

 

@property(nonatomic,copy)NSString *name;

 

-(void)printName;

 

@end


MyClass.m:


#import "MyClass.h"

 

@implementationMyClass

 

-(void)printName

{

    NSLog(@"%@",@"MyClass");

}

 

@end

 

@implementation MyClass(MyAddition)

 

-(void)printName

{

    NSLog(@"%@",@"MyAddition");

}

 

@end



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


clang -rewrite-objc MyClass.m


好吧,我们得到了一个3M大小,10w多行的.cpp文件(这绝对是Apple值得吐槽的一点),我们忽略掉所有和我们无关的东西,在文件的最后,我们找到了如下代码片段:


staticstruct/*_method_list_t*/{

unsignedintentsize;  // sizeof(struct _objc_method)

unsignedintmethod_count;

struct_objc_methodmethod_list[1];

}_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition __attribute__((used,section("__DATA,__objc_const"))) = {

sizeof(_objc_method),

1,

{{(structobjc_selector *)"printName","v16@0:8",(void *)_I_MyClass_MyAddition_printName}}

};

 

staticstruct/*_prop_list_t*/{

unsignedintentsize;  // sizeof(struct _prop_t)

unsignedintcount_of_properties;

struct_prop_tprop_list[1];

}_OBJC_$_PROP_LIST_MyClass_$_MyAddition __attribute__((used,section("__DATA,__objc_const"))) = {

sizeof(_prop_t),

1,

{{"name","T@"NSString",C,N"}}

};

 

extern"C"__declspec(dllexport)struct_class_tOBJC_CLASS_$_MyClass;

 

staticstruct_category_t_OBJC_$_CATEGORY_MyClass_$_MyAddition __attribute__((used,section("__DATA,__objc_const"))) =

{

"MyClass",

0,// &OBJC_CLASS_$_MyClass,

(conststruct_method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_MyClass_$_MyAddition,

0,

0,

(conststruct_prop_list_t *)&_OBJC_$_PROP_LIST_MyClass_$_MyAddition,

};

staticvoidOBJC_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"))staticvoid *OBJC_CATEGORY_SETUP[] = {

(void *)&OBJC_CATEGORY_SETUP_$_MyClass_$_MyAddition,

};

staticstruct_class_t *L_OBJC_LABEL_CLASS_$[1]__attribute__((used,section("__DATA, __objc_classlist,regular,no_dead_strip")))={

&OBJC_CLASS_$_MyClass,

};

staticstruct_class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {

&OBJC_CLASS_$_MyClass,

};

staticstruct_category_t *L_OBJC_LABEL_CATEGORY_$[1]__attribute__((used,section("__DATA, __objc_catlist,regular,no_dead_strip")))={

&_OBJC_$_CATEGORY_MyClass_$_MyAddition,

};


我们可以看到,

1)、首先编译器生成了实例方法列表OBJC$_CATEGORY_INSTANCE_METHODSMyClass$_MyAddition和属性列表OBJC$_PROP_LISTMyClass$_MyAddition,两者的命名都遵循了公共前缀+类名+category名字的命名方式,而且实例方法列表里面填充的正是我们在MyAddition这个category里面写的方法printName,而属性列表里面填充的也正是我们在MyAddition里添加的name属性。还有一个需要注意到的事实就是category的名字用来给各种列表以及后面的category结构体本身命名,而且有static来修饰,所以在同一个编译单元里我们的category名不能重复,否则会出现编译错误。


2)、其次,编译器生成了category本身OBJC$_CATEGORYMyClass$_MyAddition,并用前面生成的列表来初始化category本身。


3)、最后,编译器在DATA段下的objc_catlist section里保存了一个大小为1的category_t的数组L_OBJC_LABELCATEGORY$(当然,如果有多个category,会生成对应长度的数组^_^),用于运行期category的加载。


到这里,编译器的工作就接近尾声了,对于category在运行期怎么加载,我们下节揭晓。


4、追本溯源-category如何加载


我们知道,Objective-C的运行是依赖OC的runtime的,而OC的runtime和其他系统库一样,是OS X和iOS通过dyld动态加载的。

想了解更多dyld地同学可以移步这里(3)。


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


void_objc_init(void)

{

    staticboolinitialized = false;

    if(initialized)return;

    initialized = true;

 

    // fixme defer initialization until an objc-using image is found?

    environ_init();

    tls_init();

    lock_init();

    exception_init();

 

    // Register for unmap first, in case some +load unmaps something

    _dyld_register_func_for_remove_image(&unmap_image);

    dyld_register_image_state_change_handler(dyld_image_state_bound,

                                            1/*batch*/, &map_images);

    dyld_register_image_state_change_handler(dyld_image_state_dependents_initialized,0/*not batch*/, &load_images);

}


category被附加到类上面是在map_images的时候发生的,在new-ABI的标准下,_objc_init里面的调用的map_images最终会调用objc-runtime-new.mm里面的_read_images方法,而在_read_images方法的结尾,有以下的代码片段:


    for(EACH_HEADER){

        category_t **catlist =

            _getObjc2CategoryList(hi, &count);

        for(i = 0;icategory_t *cat = catlist[i];

            class_t *cls = remapClass(cat->cls);

 

            if(!cls){

                // Category's target class is missing (probably weak-linked).

                // Disavow any knowledge of this category.

                catlist[i] = NULL;

                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.

            BOOLclassExists = NO;

            if(cat->instanceMethods ||  cat->protocols

                ||  cat->instanceProperties)

            {

                addUnattachedCategoryForClass(cat,cls,hi);

                if(isRealized(cls)){

                    remethodizeClass(cls);

                    classExists = YES;

                }

                if(PrintConnecting){

                    _objc_inform("CLASS: found category -%s(%s) %s",

                                getName(cls),cat->name,

                                classExists?"on existing class" : "");

                }

            }

 

            if(cat->classMethods  ||  cat->protocols

                /* ||  cat->classProperties */)

            {

                addUnattachedCategoryForClass(cat,cls->isa,hi);

                if(isRealized(cls->isa)){

                    remethodizeClass(cls->isa);

                }

                if(PrintConnecting){

                    _objc_inform("CLASS: found category +%s(%s)",

                                getName(cls),cat->name);

                }

            }

        }

    }


首先,我们拿到的catlist就是上节中讲到的编译器为我们准备的category_t数组,关于是如何加载catlist本身的,我们暂且不表,这和category本身的关系也不大,有兴趣的同学可以去研究以下Apple的二进制格式和load机制。

略去PrintConnecting这个用于log的东西,这段代码很容易理解:


1)、把category的实例方法、协议以及属性添加到类上

2)、把category的类方法和协议添加到类的metaclass上


值得注意的是,在代码中有一小段注释 / || cat->classProperties /,看来苹果有过给类添加属性的计划啊。


ok,我们接着往里看,category的各种列表是怎么最终添加到类上的,就拿实例方法列表来说吧:


在上述的代码片段里,addUnattachedCategoryForClass只是把类和category做一个关联映射,而remethodizeClass才是真正去处理添加事宜的功臣。


staticvoidremethodizeClass(class_t *cls)

{

    category_list *cats;

    BOOLisMeta;

 

    rwlock_assert_writing(&runtimeLock);

 

    isMeta = isMetaClass(cls);

 

    // Re-methodizing: check for more categories

    if((cats = unattachedCategoriesForClass(cls))){

        chained_property_list *newproperties;

        constprotocol_list_t **newprotos;

 

        if(PrintConnecting){

            _objc_inform("CLASS: attaching categories to class '%s' %s",

                        getName(cls),isMeta?"(meta)" : "");

        }

 

        // Update methods, properties, protocols

 

        BOOLvtableAffected = NO;

        attachCategoryMethods(cls,cats, &vtableAffected);

 

        newproperties = buildPropertyList(NULL,cats,isMeta);

        if(newproperties){

            newproperties->next = cls->data()->properties;

            cls->data()->properties = newproperties;

        }

 

        newprotos = buildProtocolList(cats,NULL,cls->data()->protocols);

        if(cls->data()->protocols  &  cls->data()->protocols != newprotos){

            _free_internal(cls->data()->protocols);

        }

        cls->data()->protocols = newprotos;

 

        _free_internal(cats);

 

        // Update method caches and vtables

        flushCaches(cls);

        if(vtableAffected)flushVtables(cls);

    }

}


而对于添加类的实例方法而言,又会去调用attachCategoryMethods这个方法,我们去看下attachCategoryMethods:

staticvoid

attachCategoryMethods(class_t *cls,category_list *cats,

                      BOOL *inoutVtablesAffected)

{

    if(!cats)return;

    if(PrintReplacedMethods)printReplacements(cls,cats);

 

    BOOLisMeta = isMetaClass(cls);

    method_list_t **mlists = (method_list_t **)

        _malloc_internal(cats->count *sizeof(*mlists));

 

    // Count backwards through cats to get newest categories first

    intmcount = 0;

    inti = cats->count;

    BOOLfromBundle = NO;

    while(i--){

        method_list_t *mlist = cat_method_list(cats->list[i].cat,isMeta);

        if(mlist){

            mlists[mcount++] = mlist;

            fromBundle |= cats->list[i].fromBundle;

        }

    }

 

    attachMethodLists(cls,mlists,mcount,NO,fromBundle,inoutVtablesAffected);

 

    _free_internal(mlists);

 

}


0 0