OC category的实现原理

本文载自:  http://blog.csdn.net/a316212802/article/details/49894421

挑灯细览-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_t cls;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@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@implementationMyClass(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_method method_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_t prop_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_t OBJC_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_METHODS_MyClass$MyAddition和属性列表_OBJC$PROP_LIST_MyClass$MyAddition,两者的命名都遵循了公共前缀+类名+category名字的命名方式,而且实例方法列表里面填充的正是我们在MyAddition这个category里面写的方法printName,而属性列表里面填充的也正是我们在MyAddition里添加的name属性。还有一个需要注意到的事实就是category的名字用来给各种列表以及后面的category结构体本身命名,而且有static来修饰,所以在同一个编译单元里我们的category名不能重复,否则会出现编译错误。

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

3)、最后,编译器在DATA段下的objc_catlist section里保存了一个大小为1的category_t的数组L_OBJC_LABEL_CATEGORY$(当然,如果有多个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方法的结尾,有以下的代码片段:

// Discover categories.for(EACH_HEADER) {        category_t **catlist =            _getObjc2CategoryList(hi, &count);for(i =0; i < count; i++) {            category_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.BOOL classExists = 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;    BOOL isMeta;    rwlock_assert_writing(&runtimeLock);    isMeta = isMetaClass(cls);// Re-methodizing: check for more categoriesif((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, protocolsBOOL vtableAffected = 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 vtablesflushCaches(cls);if(vtableAffected) flushVtables(cls);    }}

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

staticvoidattachCategoryMethods(class_t *cls, category_list *cats,                      BOOL *inoutVtablesAffected){if(!cats)return;if(PrintReplacedMethods) printReplacements(cls, cats);    BOOL isMeta = isMetaClass(cls);    method_list_t **mlists = (method_list_t **)        _malloc_internal(cats->count *sizeof(*mlists));// Count backwards through cats to get newest categories firstintmcount =0;inti = cats->count;    BOOL fromBundle = 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);}

attachCategoryMethods做的工作相对比较简单,它只是把所有category的实例方法列表拼成了一个大的实例方法列表,然后转交给了attachMethodLists方法(我发誓,这是本节我们看的最后一段代码了^_^),这个方法有点长,我们只看一小段:

for(uint32_t m =0;            (scanForCustomRR || scanForCustomAWZ)  &&  m < mlist->count;            m++)        {            SEL sel = method_list_nth(mlist, m)->name;if(scanForCustomRR  &&  isRRSelector(sel)) {                cls->setHasCustomRR();                scanForCustomRR =false;            }elseif(scanForCustomAWZ  &&  isAWZSelector(sel)) {                cls->setHasCustomAWZ();                scanForCustomAWZ =false;            }        }// Fill method list arraynewLists[newCount++] = mlist;    .    .    .// Copy old methods to the method list arrayfor(i =0; i < oldCount; i++) {        newLists[newCount++] = oldLists[i];    }

需要注意的有两点:

1)、category的方法没有“完全替换掉”原来类已经有的方法,也就是说如果category和原来类都有methodA,那么category附加完成之后,类的方法列表里会有两个methodA

2)、category的方法被放到了新方法列表的前面,而原来类的方法被放到了新方法列表的后面,这也就是我们平常所说的category的方法会“覆盖”掉原来类的同名方法,这是因为运行时在查找方法的时候是顺着方法列表的顺序查找的,它只要一找到对应名字的方法,就会罢休^_^,殊不知后面可能还有一样名字的方法。

5、旁枝末叶-category和+load方法

我们知道,在类和category中都可以有+load方法,那么有两个问题:

1)、在类的+load方法调用的时候,我们可以调用category中声明的方法么?

2)、这么些个+load方法,调用顺序是咋样的呢?

鉴于上述几节我们看的代码太多了,对于这两个问题我们先来看一点直观的:

我们的代码里有MyClass和MyClass的两个category (Category1和Category2),MyClass和两个category都添加了+load方法,并且Category1和Category2都写了MyClass的printName方法。

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

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

objc[1187]: REPLACED: -[MyClass printName] by category Category1

objc[1187]: REPLACED: -[MyClass printName] by category Category2

.

.

.

objc[1187]: LOAD: class 'MyClass' scheduled for +load

objc[1187]: LOAD: category 'MyClass(Category1)' scheduled for +load

objc[1187]: LOAD: category 'MyClass(Category2)' scheduled for +load

objc[1187]: LOAD: +[MyClass load]

.

.

.

objc[1187]: LOAD: +[MyClass(Category1) load]

.

.

.

objc[1187]: LOAD: +[MyClass(Category2) load]

所以,对于上面两个问题,答案是很明显的:

1)、可以调用,因为附加category到类的工作会先于+load方法的执行

2)、+load的执行顺序是先类,后category,而category的+load执行顺序是根据编译顺序决定的。

目前的编译顺序是这样的:

我们调整一个Category1和Category2的编译顺序,run。ok,我们可以看到控制台的输出顺序变了:

objc[1187]: REPLACED: -[MyClass printName] by category Category2

objc[1187]: REPLACED: -[MyClass printName] by category Category1

.

.

.

objc[1187]: LOAD: class 'MyClass' scheduled for +load

objc[1187]: LOAD: category 'MyClass(Category2)' scheduled for +load

objc[1187]: LOAD: category 'MyClass(Category1)' scheduled for +load

objc[1187]: LOAD: +[MyClass load]

.

.

.

objc[1187]: LOAD: +[MyClass(Category2) load]

.

.

.

objc[1187]: LOAD: +[MyClass(Category1) load]

虽然对于+load的执行顺序是这样,但是对于“覆盖”掉的方法,则会先找到最后一个编译的category里的对应方法。

这一节我们只是用很直观的方式得到了问题的答案,有兴趣的同学可以继续去研究一下OC的运行时代码。

6、触类旁通-category和方法覆盖

鉴于上面几节我们已经把原理都讲了,这一节只有一个问题:

怎么调用到原来类中被category覆盖掉的方法?

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

Class currentClass = [MyClass class];MyClass *my = [[MyClass alloc] init];if(currentClass) {unsignedintmethodCount;    Method *methodList = class_copyMethodList(currentClass, &methodCount);    IMP lastImp =NULL;    SEL lastSel =NULL;for(NSIntegeri =0; i < methodCount; i++) {        Method method = methodList[i];NSString*methodName = [NSStringstringWithCString:sel_getName(method_getName(method))                                        encoding:NSUTF8StringEncoding];if([@"printName"isEqualToString:methodName]) {            lastImp = method_getImplementation(method);            lastSel = method_getName(method);        }    }typedefvoid(*fn)(id,SEL);if(lastImp !=NULL) {        fn f = (fn)lastImp;        f(my,lastSel);    }    free(methodList);}

7、更上一层-category和关联对象

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

MyClass+Category1.h:

#import"MyClass.h"@interfaceMyClass(Category1)@property(nonatomic,copy)NSString*name;@end

MyClass+Category1.m:

#import"MyClass+Category1.h"#import@implementationMyClass(Category1)+ (void)load{NSLog(@"%@",@"load in Category1");}- (void)setName:(NSString*)name{    objc_setAssociatedObject(self,"name",                            name,                            OBJC_ASSOCIATION_COPY);}- (NSString*)name{NSString*nameObject = objc_getAssociatedObject(self,"name");returnnameObject;}@end

但是关联对象又是存在什么地方呢? 如何存储? 对象销毁时候如何处理关联对象呢?

我们去翻一下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 existsObjectAssociationMap *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 =newObjectAssociationMap;                associations[disguised_object] = refs;                (*refs)[key] = ObjcAssociation(policy, new_value);                _class_setInstancesHaveAssociatedObjects(_object_getClass(object));            }        }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定义如下:

classAssociationsManager {staticOSSpinLock _lock;staticAssociationsHashMap *_map;// associative references:  object pointer -> PtrPtrHashMap.public:    AssociationsManager()  { OSSpinLockLock(&_lock); }    ~AssociationsManager()  { OSSpinLockUnlock(&_lock); }    AssociationsHashMap &associations() {if(_map == NULL)            _map =newAssociationsHashMap();return*_map;    }};

AssociationsManager里面是由一个静态AssociationsHashMap来存储所有的关联对象的。这相当于把所有对象的关联对象都存在一个全局map里面。而map的的key是这个对象的指针地址(任意两个不同对象的指针地址一定是不同的),而这个map的value又是另外一个AssociationsHashMap,里面保存了关联对象的kv对。

而在对象的销毁逻辑里面,见objc-runtime-new.mm:

void*objc_destructInstance(id obj) {if(obj) {        Class isa_gen = _object_getClass(obj);        class_t *isa = newcls(isa_gen);// Read all of the flags at once for performance.boolcxx = hasCxxStructors(isa);boolassoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen);// This order is important.if(cxx) object_cxxDestruct(obj);if(assoc) _object_remove_assocations(obj);if(!UseGC) objc_clear_deallocating(obj);    }returnobj;}

嗯,runtime的销毁对象函数objc_destructInstance里面会判断这个对象有没有关联对象,如果有,会调用_object_remove_assocations做关联对象的清理工作。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容