前言
Objective-C中所有的类,以及分类都是基于Runtime实现的。
为什么要写这篇
通过之前的学习,笔者已经了解了分类的大致底层实现流程。想通过自己阅读源码的方式加深一下印象
1.Category底层结构?
OC代码:
@interface Person (Study)
@property(nonatomic,copy)NSString *studyNo;
-(void)studyEnglish;
@end
通过:
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Person+Study.m
得到转换成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; //属性
};
static struct _category_t _OBJC_$_CATEGORY_Person_$_Study __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"Person",
0, // &OBJC_CLASS_$_Person,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_Person_$_Study,
0,
0,
(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_Person_$_Study,
};
可以看出:编译成C++代码后,把分类的属性,实例方法,类方法,协议信息组成了
一个category_t类型的结构体。
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_Person_$_Study __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_objc_method),
1,
{{(struct objc_selector *)"studyEnglish", "v16@0:8", (void *)_I_Person_Study_studyEnglish}}
};
可以看出方法列表的结构体有三个属性:
entsize: _objc_method结构体的size
method_count:方法的个数
method_list:存放的方法数组
2.Category的信息是怎么加载到内存里的?
找到objc4源码中的_objc_init的方法,这是Runtime初始化方法,阅读源码一般从这里开始。
我们找到
/***********************************************************************
* remethodizeClass
* Attach outstanding categories to an existing class.
* Fixes up cls's method list, protocol list, and property list.
* Updates method caches for cls and its subclasses.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void remethodizeClass(Class cls)
{
category_list *cats;
bool isMeta;
runtimeLock.assertLocked();
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);
}
}
为什么找到这里?因为从runtime入口不断往下找看到这个函数英文的描述:* Attach outstanding categories to an existing class.:把分类信息合并到一个已存的类中。
那么具体是怎么合并的呢,用什么方式?不难找到attachLists这个方法
源码:
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
//mlists实际上是个二维数组
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) {
//mcount是从0开始的,所以最后面的Category的方法列表会在mlists最前面
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);
}
--------------------------------------------------------------------------------------------
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]));
}
}
注意:
// array()扩容
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
//将以前的list整体往后移addedCount个长度
memmove(array()->lists + addedCount, array()->lists,oldCount * sizeof(array()->lists[0]));
//将新增加的列表拷贝到以前旧列表的位置
memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
memmove、memcpy区别
memmove(void *__dst, const void *__src, size_t __len):由src所指内存区域复制count个字节到dest所指内存区域:由src所指内存区域复制count个字节到dest所指内存区域。
memcpy(void *__dst, const void *__src, size_t __n):从源source所指的内存地址的起始位置开始拷贝n个字节到目标destin所指的内存地址的起始位置中。
为什么调用方法会优先调用分类的?而且是后编译的优先
从源码中得知:分类组合mlists是倒序取出category的方法列表放在mlists的前面,因此后编译的是优先调用,在把mlists组合到类的rw->methods中是先把原rw->methods里的内容往后移动mlists的count个单位,然后再把mlists拷贝到rw->methods前面。因此可得
网友评论