我们讲解的category分为三个部分:

1:怎么用:运用场景

2:不能用:争议性的特点:能做什么不能做什么

3:原因:内部原理

前言:

无论一个类设计的多么完美,在未来的需求演进中,都有可能会碰到一些无法预测的情况。那怎么扩展已有的类呢?一般而言,继承和组合是不错的选择。但是在Objective-C 2.0中,又提供了category这个语言特性,可以动态地为已有类添加新行为。Objective-C的这个语言特性对于纯动态语言来说可能不算什么,比如javascript,你可以随时为一个“类”或者对象添加任意方法和实例变量。但是对于不是那么“动态”的语言而言,这确实是一个了不起的特性。

1:怎么用:运用场景

1.1:主要作用是为已经存在的类添加方法。

想要收集每个页面的启动时间:项目中已经有上百个页面了,如果一个一个的加,浪费时间不说,以后增加了新页面,还需要添加方法。

解决方法:

我们可以发现页面都继承了UIViewController,想要在每个页面都执行的代码,可以写在这些页面的父类中。我们可以把代码写在UIViewController中,使用分类(category)。

1.2 :分类

一个类中的代码非常多,如果超过1000多行,那么在翻阅的时候也会觉得很困难,但是继承下来,再使用的时候,只能集成子类,而且方法比较多,想要直接分散开来,不是特别容易,所以可以采取分类的方式,把想通类型的代码加载在一起。

好处:可以把类的实现分开在几个不同的文件里面。这样做有几个显而易见的好处,

a)可以减少单个文件的体积

b)可以把不同的功能组织到不同的category里

c)可以由多个开发者共同完成一个类

d)可以按需加载想要的category 等等。

并且 还可以按照需要加载想要的category。


1.3:引用父类未公开方法

比如父类 XSDLabel:

// XSDLabel.h
#import <UIKit/UIKit.h>@interface XSDLabel : UILabel@end
// XSDLabel.m
#import "XSDLabel.h"@implementation XSDLabel
- (void)giveTextRandomColor {self.textColor = [UIColor orangeColor];
}
@end

XSDLabel1继承自XSDLabel:

#import <UIKit/UIKit.h>
#import "XSDLabel.h"
@interface XSDLabel1 : XSDLabel@end

现在需要在设置text时,同时设置文字颜色,调用父类的giveTextRandomColor:

#import "XSDLabel1.h"@implementation XSDLabel1- (void)setText:(NSString *)text {[super setText:text];[self giveTextRandomColor];
}@end

直接编译会报错:

编译器提示找不到父类的方法

在子类中声明父类类别后,即可通过编译:

#import "XSDLabel1.h"@interface XSDLabel (private)
- (void)giveTextRandomColor;
@end@implementation XSDLabel1- (void)setText:(NSString *)text {[super setText:text];[self giveTextRandomColor];
}@end

类别名private是任意的,但不可以缺省。

请不要乱来:苹果官方会拒绝使用系统私有API的应用上架,因此即使学会了如何调用私有方法,在遇到调用其它类的私有方法时,要谨慎处理,尽量用其它方法替代。

1.4:声明私有方法

1.5:模拟多继承

1.6:把framework的私有方法公开

2:不能用:争议性的特点:能做什么不能做什么

(如果看下面简单的原因解释不明白的 可以继续向下面看category的内部原理,讲的比较细致)


2.1:只能添加方法,不能为一个类动态的添加成员变量,可以给类动态增加方法和属性。

在类别中声明的属性,将无法存取,

原因:因为分类是动态时,此时,类的框架已经实现,属性列表里并没有给动态添加的属性赋值。其次并不是不能添加属性,而是添加一个Property,系统不会自动给他创建set和get方法,运用runtime:objc_setAssociatedObject和objc_getAssociatedObject给分类创建set和get方法。。

因为方法和属性并不“属于”类实例,而成员变量“属于”类实例。我们所说的“类实例”概念,指的是一块内存区域,包含了isa指针和所有的成员变量。所以假如允许动态修改类成员变量布局,已经创建出的类实例就不符合类定义了,变成了无效对象。但方法定义是在objc_class中管理的,不管如何增删类方法,都不影响类实例的内存布局,已经创建出的类实例仍然可正常使用。具体请看这里


2.2:类别中的方法,会“覆盖”父类中的同名方法,无法再调用父类中的方法(因为类别中无法使用super)

为防止意外覆盖,总是应该给类别加上前缀。

原因:这个不是覆盖,因为所有的类的方法和分类的方法,都会在类的方法列表中存在,类自己的是会先放进去,类别是动态添加的所以是后放入的,根据取方法的顺序,后进先出,而系统的特性是,只要找到了相同的方法便不再继续寻找,所以如果分类实现了本类的方法,会先调用分类的,如果有多个分类同时实现,那要看编译的时候哪个方法最后放入。

Category 可以实现原始类的方法:

具体原因:

1).重写原生方法之后 会覆盖掉原有的方法,因为在OC中是runtime执行 且方法执行时仅仅有一个方法会被执行,除loadView会先执行原生方法然后执行category外 其他都是执行category重写的方法体。

2).当多个地方对系统本身的方法进行了重写 则执行时系统无法知道执行哪一个方法。

3).category的出现只是为了扩展原有的类。如果需要重写 使用继承吧。


2.3:不同文件中的同名类别,同名方法,不会报错,实际执行的方法以最后一个加载的文件为准,因此使用前缀防止类别人互相覆盖。


2.4:分类中可以访问原来类中的成员变量,但是只能访问@protect和@public形式的变量。如果想要访问本类中的私有变量,分类和子类一样,只能通过方法来访问。

2.5:category和Extension延展不同。

原因:

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

想知道详细区别的,请看这里

小记:

我自己写了一个分类,通过runtime来获取类的方法和属性,发现分类方法和本类方法在一个方法列表,引用不引用都在,只是引用之后,在类里就可以用这个分类的方法。不引用的话,编译器找不到方法,就会报错。

3:原因:内部原理

现在讲解最重要的内部原理,上面的有争议的特性还没有彻底明白为啥的 可以细细看下面。

3.1: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)

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;

从category的定义也可以看出category的可为(可以添加实例方法,类方法,甚至可以实现协议,添加属性)和不可为(无法添加实例变量)。
ok,我们先去写一个category看一下category到底为何物:

MyClass.h:

#import <Foundation/Foundation.h>@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

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

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"}}
};extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_MyClass;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,
};
static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {
&OBJC_CLASS_$_MyClass,
};
static struct _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在运行期怎么加载,我们下节揭晓。

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

我们知道,Objective-C的运行是依赖OC的runtime的,而OC的runtime和其他系统库一样,是OS X和iOS通过dyld动态加载的。对于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();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才是真正去处理添加事宜的功臣。

static void remethodizeClass(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;const protocol_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:

static void
attachCategoryMethods(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 firstint mcount = 0;int i = 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;} else if (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的方法会“覆盖”掉原来类的同名方法,这是因为运行时在查找方法的时候是顺着方法列表的顺序查找的,它只要一找到对应名字的方法,就会罢休^_^,殊不知后面可能还有一样名字的方法。

3.3:旁枝末叶-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的运行时代码。

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

鉴于上面几节我们已经把原理都讲了,这一节只有一个问题:
怎么调用到原来类中被category覆盖掉的方法?
对于这个问题,我们已经知道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);
}


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

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

MyClass+Category1.h:

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

MyClass+Category1.m:

#import "MyClass+Category1.h"
#import <objc/runtime.h>@implementation MyClass (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");return nameObject;
}@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 = new ObjectAssociationMap;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定义如下:

class AssociationsManager {static OSSpinLock _lock;static AssociationsHashMap *_map;               // associative references:  object pointer -> PtrPtrHashMap.
public:AssociationsManager()   { OSSpinLockLock(&_lock); }~AssociationsManager()  { OSSpinLockUnlock(&_lock); }AssociationsHashMap &associations() {if (_map == NULL)_map = new AssociationsHashMap();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.bool cxx = hasCxxStructors(isa);bool assoc = !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);}return obj;
}

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

这个是从大牛的网址里看的资料,顺便整理下来,连接地址:

http://tech.meituan.com/DiveIntoCategory.html(这里是内部原理讲解,很透彻)

http://www.jianshu.com/p/2bf61807b6b3

感谢大神:都是大神的精华,我整理成自己需要学习的效果以便以后自己快速查阅。

category-内部原理、运用场景、特点相关推荐

  1. iOS runtime 底层详解、内部原理、场景应用

    前言学:位域和共用体 一:isa指针--runtime之前的学习 1.1:苹果应用的按位或.按位与 二:类对象信息 2.1:类对象信息:rw_t 2.2:类对象信息:方法缓存(很关键) 2.2:类对象 ...

  2. 【iOS开发】——Category底层原理、Extension、关联对象

    [iOS开发]--Category底层原理.Extension.关联对象 Category是什么?它可以用来干什么? Category特点 Category的实质以及实现过程 Category结构体 ...

  3. Git详解之九 Git内部原理

    以下内容转载自:http://www.open-open.com/lib/view/open1328070620202.html Git 内部原理 不管你是从前面的章节直接跳到了本章,还是读完了其余各 ...

  4. git gui fetch不到文件_Git内部原理剖析,有比这还详细的吗?

    1.1. 为什么写这篇文章 写这篇文章的本意有二: 工作安排原因,常有同事询问我一些关于 Git 的问题,总觉得自己解释的不够透彻,因此觉得有必要深入了解一下. 目前中文的 Git 教程往往本末倒置, ...

  5. Mongodb存储特性与内部原理

    前言 本文重点叙述下mongodb存储特性和内部原理, 下一篇文章咱们一起来搭建下Replica Sets+Sharded Cluster的集群 存储引擎 wiredTiger引擎 1.3.0新增引擎 ...

  6. 内部存储_Mongodb存储特性与内部原理

    前言 本文重点叙述下mongodb存储特性和内部原理, 下一篇文章咱们一起来搭建下Replica Sets+Sharded Cluster的集群 存储引擎 wiredTiger引擎 1.3.0新增引擎 ...

  7. git(9)Git 内部原理

    9 Git 内部原理 不管你是从前面的章节直接跳到了本章,还是读完了其余各章一直到这,你都将在本章见识 Git 的内部工作原理和实现方式.我个人发现学习这些内容对于理解 Git 的用处和强大是非常重要 ...

  8. 跨越原理优缺点_jsonp的原理,应用场景,优缺点

    在开发测试中,难免会在不同域下进行跨域操作,出于安全性考虑,浏览器中的同源策略阻止从一个域上加载的脚本获取或者操作 另一个域下的文档属性,这时需要进行跨域的方式进行解决,如:使用jsonp ,ifra ...

  9. 37 | MySQL的内部临时表使用场景?(Group by语句使用注意事项)

    一.前言 在执行语句时候,记得多"食用"explian看看语句性能如何? create table t1(id int primary key, a int, b int, ind ...

  10. hutool的定时任务不支持依赖注入怎么办_分布式任务调度平台xxljob的内部原理,及在转转的落地实践...

    让世界因流转更美好 值此教师节来临之际,衷心祝愿所有的老师教师节快乐,身体健康,幸福平安,工作顺利,桃李满天下.您们辛苦了! 作者简介 · 杜云杰,架构师,转转架构部负责人,负责服务治理.MQ.云平台 ...

最新文章

  1. 关于深度残差收缩网络,你需要知道这几点
  2. 独家发布 | 产品经理生存现状
  3. Vim和Vi的常用命令
  4. 《Android游戏开发详解》一2.18 使用Java API中的对象
  5. 云计算实战系列七(管道及重定向)
  6. mysql免安装_腾讯云Ubuntu18.04部置Django2系列(二):Ubuntu18.04 安装Mysql
  7. 计算机应用杂志投稿,计算机类杂志 (可网上投稿)
  8. 驴妈妈、途牛们该如何收割亲子游市场的红利?
  9. 四个简单的步骤告别烦人的flash广告
  10. 常见笔顺错误的字_容易出错的汉字|汉字中哪些字笔顺容易错
  11. PS里面如何批处理图片
  12. sys matlab,matlab中sys什么意思
  13. python二维码生成识别代码_Python学习案例之二维码生成识别
  14. 微信小程序-wxml笔记(更新中)
  15. 多可系统如何设置登录IP限制
  16. 拍摄高质量数码照片的三条原则:安全快门、低感光度、最佳光圈
  17. 人体三维重建SMPL、SMPLX、SMPLifyX学习笔记
  18. 英语学习之沪江整理 20141101
  19. 聊天没有表情包被嘲讽,程序员直接用python爬取了十万张表情包
  20. 搜索引擎发展趋势探讨

热门文章

  1. XStream null值序列化时不会显示标签
  2. python打字_Python编写打字训练小程序
  3. 虚拟桌面更新,自定义快捷键
  4. python自动下载小说
  5. Xmarks无法同步问题解决(转)
  6. shell学习(一)简单示例help用法
  7. c语言转义字符o用法,gogo体育下载官网-gogo体育下载官网
  8. 芯片积累及封装(hdc1080、EL357N-G、74HC_HCT4052、XL6009、lm7805、LM393-D、irlr3410、BST-BMP280-DS001-19)
  9. 2020年中国报废汽车拆解回收行业市场现状分析,汽车报废率远低于发达国家「图」
  10. 易语言 文件捆绑机的原理【转载】