写博客只是为了让自己学的更深刻,参考: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探究的更多相关文章

  1. OC中分类(Category)和扩展(Extension)

    1.分类的定义 category是Objective-C 2.0之后添加的语言特性,中文也有人称之为分类.类别.Category的主要作用是为已经存在的类添加方法.这个大家可能用过很多,如自己给UIC ...

  2. 分类(Category)的本质 及其与类扩展(Extension) /继承(Inherit)的区别

    1.分类的概念 分类是为了扩展系统类的方法而产生的一种方式,其作用就是在不修改原有类的基础上,为一个类扩展方法,最主要的是可以给系统类扩展我们自己定义的方法. 如何创建一个分类?↓↓ ()Cmd+N, ...

  3. 从C#到Objective-C,循序渐进学习苹果开发(3)--分类(category)和协议Protocal的理解

    本随笔系列主要介绍从一个Windows平台从事C#开发到Mac平台苹果开发的一系列感想和体验历程,本系列文章是在起步阶段逐步积累的,希望带给大家更好,更真实的转换历程体验.本文继续上一篇随笔<从 ...

  4. 关于ios object-c 类别-分类 category 的静态方法与私有变量,协议 protocol

    关于ios object-c 类别-分类 category 的静态方法与私有变量,协议 protocol 2014-02-18 19:57 315人阅读 评论(0) 收藏 举报 1.category, ...

  5. Objective-C分类 (category)和扩展(Extension)

    1.分类(category) 使用Object-C中的分类,是一种编译时的手段,允许我们通过给一个类添加方法来扩充它(但是通过category不能添加新的实例变量),并且我们不需要访问类中的代码就可以 ...

  6. OC的特有语法-分类Category、 类的本质、description方法、SEL、NSLog输出增强、点语法、变量作用域、@property @synthesize关键字、Id、OC语言构造方法

    一. 分类-Category 1. 基本用途:Category  分类是OC特有的语言,依赖于类. ➢ 如何在不改变原来类模型的前提下,给类扩充一些方法?有2种方式 ● 继承 ● 分类(Categor ...

  7. iOS之分类(category)

    1.分类(category)的作用 1.1作用:可以在不修改原来类的基础上,为一个类扩展方法.1.2最主要的用法:给系统自带的类扩展方法. 2.分类中能写点啥? 2.1分类中只能添加“方法”,不能增加 ...

  8. Objective-C:继承、分类(Category、extension)、协议(protocol),个人理解,仅供参考

    总结:继承.分类(Category.extension).协议(protocol)   一.继承: (1)特点: 继承多用于一般父类中的方法功能比较齐全,子类从父类继承过来使用,可以省略很多重复的代码 ...

  9. Objective-C:分类(Category、extension)

    分类(Category .Extension) (一)分类的划分     (2) 1.(命名的类别)类别Category:只能添加新的方法,不能添加新变量.           2.(未命名的类别)类 ...

随机推荐

  1. 4.4、Android Studio在命令行运行Gradle

    默认情况下,在你的Gradle构建设置中有两种构建类型:一种是为了调试你的应用,debug类型:一种是构建最终的发布版本,release类型.无论你使用哪种模式,你的app必须在安装到设备或虚拟机中之 ...

  2. UNIX网络编程——Socket粘包问题

    一.两个简单概念长连接与短连接:1.长连接 Client方与Server方先建立通讯连接,连接建立后不断开, 然后再进行报文发送和接收. 2.短连接 Client方与Server每进行一次报文收发交易 ...

  3. Dalvik虚拟机

    Dalvik虚拟机是google专门为android平台开发的一个java虚拟机,但它并没有使用JVM规范.Dalvik虚拟机主要完成对象生命周期的管理.线程管理.安全和异常管理以及垃圾回收等重要功能 ...

  4. UNIX网络编程——基于UDP协议的网络程序

    一.下图是典型的UDP客户端/服务器通讯过程 下面依照通信流程,我们来实现一个UDP回射客户/服务器: #include <sys/types.h> #include <sys/so ...

  5. Android的搜索框SearchView的用法-android学习之旅(三十九)

    SearchView简介 SearchView是搜索框组件,他可以让用户搜索文字,然后显示.' 代码示例 这个示例加了衣蛾ListView用于为SearchView增加自动补全的功能. package ...

  6. 【一天一道LeetCode】#326. Power of Three

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  7. Android 优质精准的用户行为统计和日志打捞方案

    Android 自定义优质精准的用户行为和日志打捞方案 Tamic csdn博客 :http://blog.csdn.net/sk719887916/article/details/51398416 ...

  8. UNIX网络编程——基本TCP套接字编程

    一.基于TCP协议的网络程序 下图是基于TCP协议的客户端/服务器程序的一般流程: 服务器调用socket().bind().listen()完成初始化后,调用accept()阻塞等待,处于监听端口的 ...

  9. xml解析之使用dom4j的api对xml文件进行CRUD(二)

    在使用dom4j的api对xml文件进行CRUD(一)见博客http://blog.csdn.net/qq_32059827/article/details/51524330的基础上,再对做一次练习. ...

  10. rt-thread的位图调度算法分析

    转自:http://blog.csdn.net/prife/article/details/7077120 序言 期待读者 本文期待读者有C语言编程基础,后文中要分析代码,对其中的一些C语言中的简单语 ...