前言
Objective-C中所有的類,以及分類都是基于Runtime實(shí)現(xiàn)的。
為什么要寫這篇
通過之前的學(xué)習(xí),筆者已經(jīng)了解了分類的大致底層實(shí)現(xiàn)流程。想通過自己閱讀源碼的方式加深一下印象
1.Category底層結(jié)構(gòu)?
OC代碼:
@interface Person (Study)
@property(nonatomic,copy)NSString *studyNo;
-(void)studyEnglish;
@end
通過:
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Person+Study.m
得到轉(zhuǎn)換成C++文件的代碼
找到
struct _category_t {
const char *name;
struct _class_t *cls;
const struct _method_list_t *instance_methods; //實(shí)例對象方法列表
const struct _method_list_t *class_methods; //類對象方法列表
const struct _protocol_list_t *protocols; //協(xié)議方法列表
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++代碼后,把分類的屬性,實(shí)例方法,類方法,協(xié)議信息組成了
一個(gè)category_t類型的結(jié)構(gòu)體。
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}}
};
可以看出方法列表的結(jié)構(gòu)體有三個(gè)屬性:
entsize: _objc_method結(jié)構(gòu)體的size
method_count:方法的個(gè)數(shù)
method_list:存放的方法數(shù)組
2.Category的信息是怎么加載到內(nèi)存里的?
找到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);
}
}
為什么找到這里?因?yàn)閺膔untime入口不斷往下找看到這個(gè)函數(shù)英文的描述:* Attach outstanding categories to an existing class.:把分類信息合并到一個(gè)已存的類中。
那么具體是怎么合并的呢,用什么方式?不難找到attachLists這個(gè)方法
源碼:
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實(shí)際上是個(gè)二維數(shù)組
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;
//由大到小遍歷分類的方法,屬性,協(xié)議列表....。
while (i--) {
auto& entry = cats->list[i];
//拿出分類的
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
//mcount是從0開始的,所以最后面的Category的方法列表會(huì)在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()擴(kuò)容
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
//將以前的list整體往后移addedCount個(gè)長度
memmove(array()->lists + addedCount, array()->lists,oldCount * sizeof(array()->lists[0]));
//將新增加的列表拷貝到以前舊列表的位置
memcpy(array()->lists, addedLists, addedCount * sizeof(array()->lists[0]));
memmove、memcpy區(qū)別
memmove(void *__dst, const void *__src, size_t __len):由src所指內(nèi)存區(qū)域復(fù)制count個(gè)字節(jié)到dest所指內(nèi)存區(qū)域:由src所指內(nèi)存區(qū)域復(fù)制count個(gè)字節(jié)到dest所指內(nèi)存區(qū)域。
memcpy(void *__dst, const void *__src, size_t __n):從源source所指的內(nèi)存地址的起始位置開始拷貝n個(gè)字節(jié)到目標(biāo)destin所指的內(nèi)存地址的起始位置中。
為什么調(diào)用方法會(huì)優(yōu)先調(diào)用分類的?而且是后編譯的優(yōu)先
從源碼中得知:分類組合mlists是倒序取出category的方法列表放在mlists的前面,因此后編譯的是優(yōu)先調(diào)用,在把mlists組合到類的rw->methods中是先把原rw->methods里的內(nèi)容往后移動(dòng)mlists的count個(gè)單位,然后再把mlists拷貝到rw->methods前面。因此可得