一、Category概念?
Category
是Objective-C 2.0之后添加的语言特性,分类、类别其实都是指的Category
。Category
的主要作用是为已经存在的类添加方法。
可以把类的实现分开在几个不同的文件里面,这样做有几个好处,如下
- 1.减少单个文件的体积
- 2.把不同的功能组织到不同的category里
- 3.由多个开发者共同完成一个类
- 4.按需加载想要的category
- 5.声明私有方法
二、Category源码分析
RMPerson
#import <Foundation/Foundation.h>
@interface RMPerson : NSObject
@end
#import "RMPerson.h"
@implementation RMPerson
@end
RMPerson+(Test)
#import "RMPerson.h"
@interface RMPerson (Test) <NSCopying>
- (void)text;
+ (void)text1;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) double weight;
@end
----------------------------------------------------------
#import "RMPerson+Test.h"
@implementation RMPerson (Test)
- (void)text {
NSLog(@"TEST---111111111111");
}
+ (void)text1 {
NSLog(@"TEST---222222222222");
}
@end
RMPerson类和RMPerson分类-RMPerson+(Test),我们通过xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc RMPerson+(Test).m
将RMPerson+(Test)
转换成C/C++源码。窥探下源码的内容(由于内容比较多,上重要的部分)
分类结构体
struct _category_t {
const char *name; //类名称
struct _class_t *cls; //类指针
const struct _method_list_t *instance_methods; //对象方法列表
const struct _method_list_t *class_methods; //类方法列表
const struct _protocol_list_t *protocols; //协议方法列表
const struct _prop_list_t *properties; //属性列表
};
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
// Discover categories.
for (EACH_HEADER) {
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)
{
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);
}
}
}
}
}
由上面源码我们阅读可得出
- 1.将分类的对象方法、对象协议方法、对象属性整理到类对象中
- 2.将分类的类方法整理到元类对象中
而从源码中,我们可注意到,无论哪种整理都是通过调用static void remethodizeClass(Class cls)
函数来重新整理类的数据,下面我们来看看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);
}
}
这个函数的主要作用是将 Category 中的方法、属性和协议整合到类(主类或元类)中,然后通过数据字段 data() 得到类对象里面的数据,将 所有分类的对象方法、属性、协议,通过attachCategoryMethods函数附加到类对象的方法列表中
,而attachCategoryMethods
函数才是正在处理Category方法的
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);
}
attachLists函数
里主要的是memmove函数
和memcpy函数
,memmove函数
将原来的方法往后移动了addedCount(分类的方法数量)
个位置,memcpy函数
将分类的方法添加到原来类方法列表的位置,这样就完美将分类的方法、协议、属性添加到了类信息中
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;
// array()->lists 原来的方法列表
memmove(array()->lists + addedCount,
array()->lists,
oldCount * sizeof(array()->lists[0]));
// addedLists 所有分类的方法列表
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]));
}
}
贴一下源码的阅读顺序,有兴趣的同学可以下载源码阅读一下:
源码解读顺序,如下
-
objc-os.mm
-
_objc_init
-
map_images
-
map_images_nolock
-
objc-runtime-new.mm
-
_read_images
-
remethodizeClass
-
attachCategories
-
attachLists
-
realloc、memmove、 memcpy
网友评论