Runtime - ③ - 分类Category探究
写博客只是为了让自己学的更深刻,参考: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;
- }
Runtime - ③ - 分类Category探究的更多相关文章
- OC中分类(Category)和扩展(Extension)
1.分类的定义 category是Objective-C 2.0之后添加的语言特性,中文也有人称之为分类.类别.Category的主要作用是为已经存在的类添加方法.这个大家可能用过很多,如自己给UIC ...
- 分类(Category)的本质 及其与类扩展(Extension) /继承(Inherit)的区别
1.分类的概念 分类是为了扩展系统类的方法而产生的一种方式,其作用就是在不修改原有类的基础上,为一个类扩展方法,最主要的是可以给系统类扩展我们自己定义的方法. 如何创建一个分类?↓↓ ()Cmd+N, ...
- 从C#到Objective-C,循序渐进学习苹果开发(3)--分类(category)和协议Protocal的理解
本随笔系列主要介绍从一个Windows平台从事C#开发到Mac平台苹果开发的一系列感想和体验历程,本系列文章是在起步阶段逐步积累的,希望带给大家更好,更真实的转换历程体验.本文继续上一篇随笔<从 ...
- 关于ios object-c 类别-分类 category 的静态方法与私有变量,协议 protocol
关于ios object-c 类别-分类 category 的静态方法与私有变量,协议 protocol 2014-02-18 19:57 315人阅读 评论(0) 收藏 举报 1.category, ...
- Objective-C分类 (category)和扩展(Extension)
1.分类(category) 使用Object-C中的分类,是一种编译时的手段,允许我们通过给一个类添加方法来扩充它(但是通过category不能添加新的实例变量),并且我们不需要访问类中的代码就可以 ...
- OC的特有语法-分类Category、 类的本质、description方法、SEL、NSLog输出增强、点语法、变量作用域、@property @synthesize关键字、Id、OC语言构造方法
一. 分类-Category 1. 基本用途:Category 分类是OC特有的语言,依赖于类. ➢ 如何在不改变原来类模型的前提下,给类扩充一些方法?有2种方式 ● 继承 ● 分类(Categor ...
- iOS之分类(category)
1.分类(category)的作用 1.1作用:可以在不修改原来类的基础上,为一个类扩展方法.1.2最主要的用法:给系统自带的类扩展方法. 2.分类中能写点啥? 2.1分类中只能添加“方法”,不能增加 ...
- Objective-C:继承、分类(Category、extension)、协议(protocol),个人理解,仅供参考
总结:继承.分类(Category.extension).协议(protocol) 一.继承: (1)特点: 继承多用于一般父类中的方法功能比较齐全,子类从父类继承过来使用,可以省略很多重复的代码 ...
- Objective-C:分类(Category、extension)
分类(Category .Extension) (一)分类的划分 (2) 1.(命名的类别)类别Category:只能添加新的方法,不能添加新变量. 2.(未命名的类别)类 ...
随机推荐
- linux常用的压缩与解压缩命令
1.gzip 压缩 gzip 是压缩文件,压缩之后文件后缀为.gz 用法:gzip 选项 [文件] 2.gunzip 解压 这个命令与gzip的功能刚好相反,这个是解压. 用法 gunzip 选项 [ ...
- 学习TensorFlow,浅析MNIST的python代码
在github上,tensorflow的star是22798,caffe是10006,torch是4500,theano是3661.作为小码农的我,最近一直在学习tensorflow,主要使用pyth ...
- 小文本——Cookies
http协议的无状态性导致在需要会话的场景下寸步难行,例如一个网站为了方便用户,在一段时间内登录过改网站的浏览器客户端实现自动登录,为实现这种客户端与服务器之间的会话机制需要额外的一些标识,http头 ...
- JAVA之旅(二十八)——File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤
JAVA之旅(二十八)--File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤 我们可以继续了,今天说下File 一.File概述 文件的操作是非常 ...
- SQL Server扫盲系列——安全性专题——SQL Server 2012 Security Cookbook
由于工作需要,最近研究这本书:<Microsoft SQL Server 2012 Security Cookbook>,为了总结及分享给有需要的人,所以把译文公布.预计每周最少3篇.如有 ...
- 常用Petri网模拟软件工具简介
常用Petri网模拟软件工具简介 首先要介绍的的一个非常有名的Petri 网网站--Petri Nets World: http://www.informatik.uni-hamburg. ...
- hello 内核模块
#ifndef __KERNEL__ # define __KERNEL__ #endif #ifndef MODULE # define MODULE #endif #include <lin ...
- python发送post请求
urllib2.urlopen() urlib2是使用各种协议完成打开url的一个扩展包.最简单的使用方式是调用urlopen方法,比如 def urlopen(url, data=None, tim ...
- 【算法导论】最小生成树之Prime法
关于最小生成树的概念,在前一篇文章中已经讲到,就不在赘述了.下面介绍Prime算法: 其基本思想为:从一个顶点出发,选择由该顶点出发的最小权值边,并将该边的另一个顶点包含进来,然后找出 ...
- C++异常处理 - 栈解旋,异常接口声明,异常类型和异常变量的生命周期
栈解旋(unwinding) 异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构.析构的顺序与构造的顺序相反.这一过程称为栈的解旋(unwinding). d ...