摘要
再完美的類,在未來需求的演進中也難免遇上無法預料的狀況。那該如何擴展已有的類?一般來說,繼承和組合都是不錯的選擇。而在 Objective-C 2.0 中,還提供了 category 這一語言特性,能動態地為已有類添加新行為。如今 category 已遍布 Objective-C 代碼的各個角落——從 Apple 官方 framework 到各個開源框架,從功能繁複的大型 App 到簡單的小應用,可謂無處不在。本文對 category 做了一次較為全面的梳理,希望對讀者有所裨益。
簡介
本文作者任職於美團網酒店事業部客戶端研發組。美團酒店作為全國最大的移動端酒店預訂平台,其客戶端團隊致力於用技術手段打造移動互聯網(Android、iOS)上優秀的酒店旅游類應用,為消費者提供更多質優價廉的選擇與便捷服務,努力改善人們住宿出游的選擇與消費方式。本文系學習 Objective-C runtime 源碼時整理而成,主要剖析 category 在 runtime 層的實現原理及方方面面,包含:
初入寶地——category 簡介
連類比事——category 和 extension
挑燈細覽——category 真面目
追本溯源——category 如何加載
旁枝末葉——category 和 +load 方法
觸類旁通——category 和方法覆蓋
更上一層——category 和關聯對象
1、初入寶地——category 簡介
category 是 Objective-C 2.0 之後新增的語言特性,主要作用是為已存在的類添加方法。除此之外,Apple 還推薦了它的另外兩個使用場景:
把類的實現拆分到幾個不同文件裡。好處顯而易見:a) 縮小單個文件的體積;b) 把不同功能組織到不同 category;c) 由多名開發者協作完成一個類;d) 按需加載想要的 category 等等。
聲明私有方法。
除了 Apple 推薦的場景,廣大開發者還脑洞大開,衍生出幾種新玩法:
模擬多繼承
把 framework 的私有方法公開
對純動態語言而言,這個特性或許不算稀奇,比如 JavaScript,你可以隨時給一個「類」或對象添加任意方法和實例變量。但對沒那麼「動態」的語言來說,這著實是個了不起的特性。
2、連類比事——category 和 extension
extension 看起來很像一個匿名的 category,但兩者幾乎是截然不同的東西。extension 在編譯期決議,它就是類的一部分,與頭文件裡的 @interface 和實現文件裡的 @implement 一起構成完整的類,伴隨類的產生而產生、消亡而消亡。extension 一般用來隱藏類的私有信息,你必須擁有某類的源碼才能為它添加 extension,所以無法為系統類(如 NSString)添加 extension。
category 則完全不同,它在運行期決議。
從這點差異不難推出一個事實:extension 可以添加實例變量,而 category 無法添加實例變量——因為運行期對象的內存布局已經確定,若添加實例變量就會破壞類的內部布局,對編譯型語言而言是災難性的。
3、挑燈細覽——category 真面目
我們知道,所有 OC 類和對象在 runtime 層都用 struct 表示,category 也不例外。在 runtime 層,category 用結構體 category_t(可在 objc-runtime-new.h 中找到定義)表示,它包含:
1) 類的名字(name)
2) 類(cls)
3) category 中所有給類添加的實例方法列表(instanceMethods)
4) category 中所有添加的類方法列表(classMethods)
5) category 實現的所有協議列表(protocols)
6) category 中添加的所有屬性(instanceProperties)
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;從這個定義也能看出 category 的可為(添加實例方法、類方法,甚至實現協議、添加屬性)與不可為(無法添加實例變量)。
好,我們先寫一個 category 看看它到底是什麼:
MyClass.h:
#import @interface MyClass : NSObject - (void)printName; @end @interface MyClass(MyAddition) @property(nonatomic, copy) NSString *name; - (void)printName; @end
MyClass.m:
#import "MyClass.h" @implementation MyClass - (void)printName { NSLog(@"%@",@"MyClass"); } @end @implementation MyClass(MyAddition) - (void)printName { NSLog(@"%@",@"MyAddition"); } @end我們用 clang 命令看看 category 會被編譯成什麼:
clang -rewrite-objc MyClass.m
於是我們得到了一個 3M 大小、10 萬多行的 .cpp 文件(這絕對是 Apple 值得吐槽的一點)。忽略掉所有無關內容,在文件末尾我們找到了這樣一段:
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, {{"name","T@\"NSString\",C,N"}} }; extern "C" __declspec(dllexport) struct _class_t OBJC_CLASS_$_MyClass; 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, }; static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = { &OBJC_CLASS_$_MyClass, }; static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [1] __attribute__((used, section ("__DATA, __objc_catlist,regular,no_dead_strip")))= { &_OBJC_$_CATEGORY_MyClass_$_MyAddition, };可以看到:
1) 編譯器先生成了實例方法列表 _OBJC$_CATEGORY_INSTANCE_METHODS_MyClass$_MyAddition 和屬性列表 _OBJC$_PROP_LIST_MyClass$_MyAddition,兩者的命名都遵循「公共前綴 + 類名 + category 名」的方式;實例方法列表裡填的正是 MyAddition 中寫的 printName,屬性列表裡填的也正是添加的 name 屬性。還要注意:category 的名字被用來給各列表以及後面的 category 結構體命名,且有 static 修飾,所以在同一編譯單元裡 category 名不能重復,否則會編譯報錯。
2) 接著,編譯器生成了 category 本身 _OBJC$_CATEGORY_MyClass$_MyAddition,並用前面生成的列表來初始化它。
3) 最後,編譯器在 DATA 段的 objc_catlist section 裡保存了一個大小為 1 的 category_t 數組 L_OBJC_LABEL_CATEGORY$(若有多個 category,會生成對應長度的數組),供運行期加載使用。
至此,編譯器的工作接近尾聲。category 在運行期如何加載,我們下節揭曉。
4、追本溯源——category 如何加載
我們知道,Objective-C 的運行依賴 OC 的 runtime,而 runtime 和其他系統庫一樣,由 OS X 和 iOS 通過 dyld 動態加載。想深入了解 dyld 的同學可以移步這裡。
對於 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(); lock_init(); exception_init(); // Register for unmap first, in case some +load unmaps something _dyld_register_func_for_remove_image(&unmap_image); dyld_register_image_state_change_handler(dyld_image_state_bound, 1/*batch*/, map_images); dyld_register_image_state_change_handler(dyld_image_state_dependents_initialized, 0/*not batch*/, load_images); }category 被附加到類上,發生在 map_images 階段。在 new-ABI 標準下,_objc_init 中調用的 map_images 最終會調到 objc-runtime-new.mm 的 _read_images 方法,而在 _read_images 的末尾,有以下代碼片段:
// Discover categories. for (EACH_HEADER) { category_t **catlist = _getObjc2CategoryList(hi, &count); for (i = 0; i < count; i++) { category_t *cat = catlist[i]; class_t *cls = remapClass(cat->cls); if (!cls) { // Category's target class is missing (probably weak-linked). // Disavow any knowledge of this category. catlist[i] = NULL; 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 (isRealized(cls)) { remethodizeClass(cls); classExists = YES; } if (PrintConnecting) { _objc_inform("CLASS: found category -%s(%s) %s", getName(cls), cat->name, classExists ? "on existing class" : ""); } } if (cat->classMethods || cat->protocols /* || cat->classProperties */) { addUnattachedCategoryForClass(cat, cls->isa, hi); if (isRealized(cls->isa)) { remethodizeClass(cls->isa); } if (PrintConnecting) { _objc_inform("CLASS: found category +%s(%s)", getName(cls), cat->name); } } } }首先,我們拿到的 catlist 就是上一節提到的、編譯器為我們準備好的 category_t 數組。至於 catlist 本身是如何加載的,這裡暫且不表,它與 category 本身的關係不大,感興趣的同學可以研究一下 Apple 的二進制格式和 load 機制。
略去用於 log 的 PrintConnecting,這段代碼其實很好懂:
1) 把 category 的實例方法、協議及屬性添加到類上;
2) 把 category 的類方法和協議添加到類的 metaclass 上。
值得注意的是,代碼裡有一小段注釋 / || cat->classProperties /,看來 Apple 曾有過給類添加屬性的打算。
我們接著往裡看,category 的各列表最終是如何掛到類上的。以實例方法列表為例:
在上面那段代碼裡,addUnattachedCategoryForClass 只是把類與 category 做關聯映射,而真正負責添加事宜的是 remethodizeClass。
static void remethodizeClass(class_t *cls) { category_list *cats; BOOL isMeta; rwlock_assert_writing(&runtimeLock); isMeta = isMetaClass(cls); // Re-methodizing: check for more categories if ((cats = unattachedCategoriesForClass(cls))) { chained_property_list *newproperties; const protocol_list_t **newprotos; if (PrintConnecting) { _objc_inform("CLASS: attaching categories to class '%s' %s", getName(cls), isMeta ? "(meta)" : ""); } // Update methods, properties, protocols BOOL vtableAffected = NO; attachCategoryMethods(cls, cats, &vtableAffected); newproperties = buildPropertyList(NULL, cats, isMeta); if (newproperties) { newproperties->next = cls->data()->properties; cls->data()->properties = newproperties; } newprotos = buildProtocolList(cats, NULL, cls->data()->protocols); if (cls->data()->protocols && cls->data()->protocols != newprotos) { _free_internal(cls->data()->protocols); } cls->data()->protocols = newprotos; _free_internal(cats); // Update method caches and vtables flushCaches(cls); if (vtableAffected) flushVtables(cls); } }而對於添加類的實例方法而言,還會再調用 attachCategoryMethods,我們看看它:
static void attachCategoryMethods(class_t *cls, category_list *cats, BOOL *inoutVtablesAffected) { if (!cats) return; if (PrintReplacedMethods) printReplacements(cls, cats); BOOL isMeta = isMetaClass(cls); method_list_t **mlists = (method_list_t **) _malloc_internal(cats->count * sizeof(*mlists)); // Count backwards through cats to get newest categories first int mcount = 0; int i = cats->count; BOOL fromBundle = NO; while (i--) { method_list_t *mlist = cat_method_list(cats->list[i].cat, isMeta); if (mlist) { mlists[mcount++] = mlist; fromBundle |= cats->list[i].fromBundle; } } attachMethodLists(cls, mlists, mcount, NO, fromBundle, inoutVtablesAffected); _free_internal(mlists); }attachCategoryMethods 的活兒相對簡單:它把所有 category 的實例方法列表拼成一個大列表,再交給 attachMethodLists 方法(我發誓,這是本節我們看的最後一段代碼了)。這個方法有點長,我們只看一小段:
for (uint32_t m = 0; (scanForCustomRR || scanForCustomAWZ) && m < mlist->count; m++) { SEL sel = method_list_nth(mlist, m)->name; if (scanForCustomRR && isRRSelector(sel)) { cls->setHasCustomRR(); scanForCustomRR = false; }else if (scanForCustomAWZ && isAWZSelector(sel)) { cls->setHasCustomAWZ(); scanForCustomAWZ = false; } } // Fill method list array newLists[newCount++] = mlist; . . . // Copy old methods to the method list array for (i = 0; i < oldCount; i++) { newLists[newCount++] = oldLists[i]; }有兩點要留意:
1) category 的方法並沒有「完全替換掉」類原有的方法。也就是說,如果 category 和原類都有 methodA,附加完成後類的方法列表裡會有兩個 methodA。
2) category 的方法被放到了新列表的前面,原類的方法則排在後面。這就是常說的 category 方法會「覆蓋」原類同名方法的原因——運行時查找方法是按方法列表順序進行的,一旦找到對應名字的方法就停止,殊不知後面可能還藏著同名方法。
5、旁枝末葉——category 和 +load 方法
類和 category 中都可以有 +load 方法,那麼有兩個問題:
1) 在類的 +load 方法調用時,能否調用 category 中聲明的方法?
2) 這麼多 +load 方法,調用順序如何?
鑑於前幾節代碼已經夠多,這兩個問題我們先直觀地看:

代碼裡有 MyClass 及其兩個 category(Category1 和 Category2),三者都寫了 +load 方法,且 Category1、Category2 都寫了 MyClass 的 printName 方法。
在 Xcode 中點擊 Edit Scheme,添加以下兩個環境變量(可在執行 load 方法及加載 category 時打印 log,更多變量選項見 objc-private.h):

運行項目,控制台會打印很多內容,我們只挑想要的看,順序如下:
objc[1187]: REPLACED: -[MyClass printName] by category Category1
objc[1187]: REPLACED: -[MyClass printName] by category Category2
.
.
.
objc[1187]: LOAD: class 'MyClass' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[1187]: LOAD: +[MyClass load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category1) load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category2) load]
所以,上述兩個問題的答案就很清楚了:
1) 可以調用,因為附加 category 到類的工作先於 +load 方法執行。
2) +load 的執行順序是先類、後 category,而各 category 的 +load 順序由編譯順序決定。
目前的編譯順序是這樣的:

我們把 Category1 和 Category2 的編譯順序對調一下,再 run。可以看到控制台輸出順序也跟著變了:

objc[1187]: REPLACED: -[MyClass printName] by category Category2
objc[1187]: REPLACED: -[MyClass printName] by category Category1
.
.
.
objc[1187]: LOAD: class 'MyClass' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category2)' scheduled for +load
objc[1187]: LOAD: category 'MyClass(Category1)' scheduled for +load
objc[1187]: LOAD: +[MyClass load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category2) load]
.
.
.
objc[1187]: LOAD: +[MyClass(Category1) load]
雖然 +load 的執行順序如此,但對於被「覆蓋」的方法,則會找到最後一個編譯的 category 裡的對應方法。
這一節我們只是用直觀方式得到了答案,感興趣的同學可以繼續深入研究 OC 的運行時代碼。
6、觸類旁通——category 和方法覆蓋
既然原理都講清楚了,這一節只有一個問題:
如何調用被 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); }7、更上一層——category 和關聯對象
如前所述,category 裡無法添加實例變量。但我們常常需要在 category 中關聯一些值,這時就可以借助關聯對象(Associated Object)來實現。
MyClass+Category1.h: #import "MyClass.h" @interface MyClass (Category1) @property(nonatomic,copy) NSString *name; @end MyClass+Category1.m: #import "MyClass+Category1.h" #import @implementation MyClass (Category1) + (void)load { NSLog(@"%@",@"load in Category1"); } - (void)setName:(NSString *)name { objc_setAssociatedObject(self, "name", name, OBJC_ASSOCIATION_COPY); } - (NSString*)name { NSString *nameObject = objc_getAssociatedObject(self, "name"); return nameObject; } @end但關聯對象究竟存在哪裡?如何存儲?對象銷毀時又如何處理?
翻一下 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); _class_setInstancesHaveAssociatedObjects(_object_getClass(object)); } }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 管理,其定義如下:
class AssociationsManager { static OSSpinLock _lock; static AssociationsHashMap *_map; // associative references: object pointer -> PtrPtrHashMap. public: AssociationsManager() {OSSpinLockLock(&_lock);} ~AssociationsManager() {OSSpinLockUnlock(&_lock);} AssociationsHashMap &associations() { if (_map == NULL) _map = new AssociationsHashMap(); return *_map; } };AssociationsManager 內部由一個靜態 AssociationsHashMap 存儲所有關聯對象。這相當於把所有對象的關聯對象都放進一個全局 map:map 的 key 是對象的指針地址(任意兩個不同對象的指針地址必然不同),value 又是另一個 AssociationsHashMap,裡面保存著真正的關聯對象 kv 對。
而在對象的銷毀邏輯裡(見 objc-runtime-new.mm):
void *objc_destructInstance(id obj) { if (obj) { Class isa_gen = _object_getClass(obj); class_t *isa = newcls(isa_gen); // Read all of the flags at once for performance. bool cxx = hasCxxStructors(isa); bool assoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen); // This order is important. if (cxx) object_cxxDestruct(obj); if (assoc) _object_remove_assocations(obj); if (!UseGC) objc_clear_deallocating(obj); } return obj; }可見 runtime 的銷毀對象函數 objc_destructInstance 會判斷該對象是否有關聯對象,若有,就調用 _object_remove_assocations 做清理。
後記
正如侯捷先生所言——「源碼面前,了無秘密」。Apple 的 Cocoa Touch 框架雖不開源,但 Objective-C 的 runtime 與 Core Foundation 卻完全開放源碼(可在 https://www.opensource.apple.com/tarballs/ 下載全部開源代碼)。
本系列 runtime 源碼學習將持續更新,意猶未盡的同學可自行到上述網站下載源碼研讀。行筆簡陋,如有謬誤,還望指正。