上一篇文章中,我們了解到,在編譯階段,每一個(gè)Category都是一個(gè)獨(dú)立的結(jié)構(gòu)體,其中包含實(shí)例方法、類方法、屬性和遵循的協(xié)議。具體內(nèi)容可參看
Category的本質(zhì)(一)編譯階段都做了什么?
今天,我們來看一下在運(yùn)行時(shí),是如何將方法、屬性和協(xié)議綁定到原有的類中,供我們調(diào)用。蘋果官方給我們提供了objc源碼,可以通過這個(gè)鏈接進(jìn)行下載:ojbc源碼
注意標(biāo)號(hào)最大的是最新版本,寫這篇文章時(shí),最新的編號(hào)為756.2,也就是最新版本,大家可以下載閱讀。
打開源碼后,整個(gè)項(xiàng)目其實(shí)是不能直接運(yùn)行的,因?yàn)闋可娴胶芏嘁蕾噹欤渲闷饋砜赡苄枰獋€(gè)把小時(shí)左右,但是這并不影響我們閱讀Category在運(yùn)行時(shí)所做的事情。
- 首先我們通過runtime源碼,來驗(yàn)證一下我們在上篇文章,通過clang編譯后看到的Category的結(jié)構(gòu)體,是否和runtime的實(shí)現(xiàn)是一致的。
由于我們了解到Category的實(shí)現(xiàn)是一個(gè)category_t結(jié)構(gòu)體,在項(xiàng)目中搜索 Category_t關(guān)鍵字,發(fā)現(xiàn)在objc-runtime-new.h中,有如下實(shí)現(xiàn):
struct category_t {
const char *name; ///類名
classref_t cls; ///類指針
struct method_list_t *instanceMethods; ///實(shí)例方法列表
struct method_list_t *classMethods; ///類方法列表
struct protocol_list_t *protocols; ///遵守的協(xié)議
struct property_list_t *instanceProperties; /// 實(shí)例屬性列表
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties; /// 類屬性列表
method_list_t *methodsForMeta(bool isMeta) { ///獲取實(shí)例方法列表或類方法列表
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi); ///獲取實(shí)例屬性列表和類屬性列表。
};
可以看到結(jié)構(gòu)體中的成員和我們通過clang編譯器得到的結(jié)構(gòu)體是完全一致的,只是多了兩個(gè)方法,一個(gè)是獲取方法列表,一個(gè)是獲取屬性列表。通過對比,以后有什么疑問的話,就可以放心大膽地通過clang來編譯OC代碼,查看對應(yīng)的C++代碼,剖析本質(zhì)。
記得我們的命令哦:
xcrun -sdk -iphoneos clang -arch arm64 -rewrite-objc xxx.m -o ---.cpp
- 下面我們沿著runtime的執(zhí)行順序,解讀一下Category的實(shí)現(xiàn)。
- 在Source目錄下,找到objc-os.mm文件,這是入口文件,對應(yīng)的objc_init方法就是引導(dǎo)初始化,向dyld(動(dòng)態(tài)鏈接庫)注冊鏡像文件。
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注冊鏡像文件
_dyld_objc_notify_register(&map_2_images, load_images, unmap_image);
}
然后查看注冊方法,如果是初次閱讀runtime源碼,可能會(huì)有很多疑問,為了減少不必要的疑慮,我把查找順序梳理了一下,大家可以按照這個(gè)順序,直接找到Category的執(zhí)行方法:

關(guān)鍵代碼:
// Discover categories.
for (EACH_HEADER) {
///二維數(shù)組
///【【instance_method_list,class_method_list,property_list,protocol_list】
/// 【instance_method_list,class_method_list,property_list,protocol_list】
/// 【instance_method_list,class_method_list,property_list,protocol_list】
/// 【instance_method_list,class_method_list,property_list,protocol_list】
/// 【instance_method_list,class_method_list,property_list,protocol_list】】
///由于一個(gè)類可以有多個(gè)Category,
///每個(gè)Category中包含屬性列表、實(shí)例方法列表、類方法列表和協(xié)議列表。
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);
///判斷是否由弱引用導(dǎo)致的類已經(jīng)被釋放了
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.
///向原有類注冊Category方法、屬性、協(xié)議
bool classExists = NO;
if (cat->instanceMethods || cat->protocols
|| cat->instanceProperties)
{
//綁定實(shí)例方法
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);
}
}
}
}
代碼中的關(guān)鍵部分,已經(jīng)逐行加了注釋,大家可以慢慢閱讀。
到了這里,就開始對實(shí)例方法和類方法進(jìn)行分別處理。類方法附加在元類對象(MetaClass)中,實(shí)例方法附加在類對象(Class)中。
我們下面以將實(shí)例方法添加到類對象為例,進(jìn)行講解。屬性、協(xié)議可以類比。
關(guān)鍵代碼在remethodizeClass中,將Category中的方法、屬性、協(xié)議附加到原來的類中,同時(shí)更新緩存列表。
/***********************************************************************
* 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.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);
}
}
繼續(xù)往下看,,我們發(fā)現(xiàn)attachCategories()方法,將Category附加到cls中,按照編譯順序,最后參與編譯的方法將會(huì)放在最前面。同時(shí),在將方法添加到類中以后,更新方法緩存列表。
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order,
// oldest categories first.
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));
///協(xié)議列表
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;
///從最后一個(gè)元素開始遍歷,如果多個(gè)Category中含有同名方法時(shí),
///最終導(dǎo)致的結(jié)果就是,最后參與編譯的方法優(yōu)先執(zhí)行
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);
}
其中還有一個(gè)比較重要的方法 attachLists(),值得我們關(guān)注,在這里實(shí)現(xiàn)了內(nèi)存擴(kuò)容,方法列表的移動(dòng)和賦值功能。
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;
//擴(kuò)容
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
array()->count = newCount;
//移動(dòng) memmove(dest, source, count)
//將array-list()即第一個(gè)元素開始的oldCount個(gè)元素移動(dòng)到array->list+addedCount的位置
//即將隊(duì)首的元素移動(dòng)到隊(duì)尾,開頭空出addedCount個(gè)元素
memmove(array()->lists + addedCount, array()->lists,
oldCount * sizeof(array()->lists[0]));
//賦值
//把a(bǔ)ddedList移動(dòng)到隊(duì)首,占據(jù)addedCount個(gè)位置
//即Category中的方法/屬性/協(xié)議添加到列表開始的位置
//這就是我們使用Category時(shí),如果添加和原有方法同名方法時(shí),會(huì)優(yōu)先執(zhí)行我們通過Category添加的方法的原因了。
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]));
}
}
關(guān)鍵部分都有注釋,希望大家可以看得明白。