摘要
無論一個類設計的多么完美,在未來的需求演進中,都有可能會碰到一些無法預測的情況。那怎么擴展已有的類呢?一般而言,繼承和組合是不錯的選擇。但是在Objective-C 2.0中,又提供了category這個語言特性,可以動態地為已有類添加新行為。如今category已經遍布于Objective-C代碼的各個角落,從Apple官方的framework到各個開源框架,從功能繁復的大型APP到簡單的應用,catagory無處不在。本文對category做了比較全面的整理,希望對讀者有所裨益。
簡介
本文作者來自美團酒店旅游事業群iOS研發組。我們致力于創造價值、提升效率、追求卓越。歡迎大家加入我們(簡歷請發送到郵箱majia03@meituan.com)。
本文系學習Objective-C的runtime源碼時整理所成,主要剖析了category在runtime層的實現原理以及和category相關的方方面面,內容包括:
- 初入寶地-category簡介
- 連類比事-category和extension
- 挑燈細覽-category真面目
- 追本溯源-category如何加載
- 旁枝末葉-category和+load方法
- 觸類旁通-category和方法覆蓋
- 更上一層-category和關聯對象
1、初入寶地-category簡介
category是Objective-C 2.0之后添加的語言特性,category的主要作用是為已經存在的類添加方法。除此之外,apple還推薦了category的另外兩個使用場景1
- 可以把類的實現分開在幾個不同的文件里面。這樣做有幾個顯而易見的好處,a)可以減少單個文件的體積 b)可以把不同的功能組織到不同的category里 c)可以由多個開發者共同完成一個類 d)可以按需加載想要的category 等等。
- 聲明私有方法
不過除了apple推薦的使用場景,廣大開發者腦洞大開,還衍生出了category的其他幾個使用場景:
- 模擬多繼承
- 把framework的私有方法公開
Objective-C的這個語言特性對于純動態語言來說可能不算什么,比如javascript,你可以隨時為一個“類”或者對象添加任意方法和實例變量。但是對于不是那么“動態”的語言而言,這確實是一個了不起的特性。
2、連類比事-category和extension
extension看起來很像一個匿名的category,但是extension和有名字的category幾乎完全是兩個東西。 extension在編譯期決議,它就是類的一部分,在編譯期和頭文件里的@interface以及實現文件里的@implement一起形成一個完整的類,它伴隨類的產生而產生,亦隨之一起消亡。extension一般用來隱藏類的私有信息,你必須有一個類的源碼才能為一個類添加extension,所以你無法為系統的類比如NSString添加extension。(詳見2)
但是category則完全不一樣,它是在運行期決議的。
就category和extension的區別來看,我們可以推導出一個明顯的事實,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的可為(可以添加實例方法,類方法,甚至可以實現協議,添加屬性)和不可為(無法添加實例變量)。
ok,我們先去寫一個category看一下category到底為何物:
MyClass.h:
#import <Foundation/Foundation.h>
@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大小,10w多行的.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_METHODSMyClass$_MyAddition和屬性列表OBJC$_PROP_LISTMyClass$_MyAddition,兩者的命名都遵循了公共前綴+類名+category名字的命名方式,而且實例方法列表里面填充的正是我們在MyAddition這個category里面寫的方法printName,而屬性列表里面填充的也正是我們在MyAddition里添加的name屬性。還有一個需要注意到的事實就是category的名字用來給各種列表以及后面的category結構體本身命名,而且有static來修飾,所以在同一個編譯單元里我們的category名不能重復,否則會出現編譯錯誤。
2)、其次,編譯器生成了category本身OBJC$_CATEGORYMyClass$_MyAddition,并用前面生成的列表來初始化category本身。
3)、最后,編譯器在DATA段下的objc_catlist section里保存了一個大小為1的category_t的數組L_OBJC_LABELCATEGORY$(當然,如果有多個category,會生成對應長度的數組_),用于運行期category的加載。
到這里,編譯器的工作就接近尾聲了,對于category在運行期怎么加載,我們下節揭曉。
4、追本溯源-category如何加載
我們知道,Objective-C的運行是依賴OC的runtime的,而OC的runtime和其他系統庫一樣,是OS X和iOS通過dyld動態加載的。
想了解更多dyld地同學可以移步這里(3)。
對于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機制。
略去PrintConnecting這個用于log的東西,這段代碼很容易理解:
1)、把category的實例方法、協議以及屬性添加到類上
2)、把category的類方法和協議添加到類的metaclass上
值得注意的是,在代碼中有一小段注釋 //cat->classProperties ,看來蘋果有過給類添加屬性的計劃啊。
ok,我們接著往里看,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這個方法,我們去看下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,那么category附加完成之后,類的方法列表里會有兩個methodA
2)、category的方法被放到了新方法列表的前面,而原來類的方法被放到了新方法列表的后面,這也就是我們平常所說的category的方法會“覆蓋”掉原來類的同名方法,這是因為運行時在查找方法的時候是順著方法列表的順序查找的,它只要一找到對應名字的方法,就會罷休_,殊不知后面可能還有一樣名字的方法。
5、旁枝末葉-category和+load方法
我們知道,在類和category中都可以有+load方法,那么有兩個問題:
1)、在類的+load方法調用的時候,我們可以調用category中聲明的方法么?
2)、這么些個+load方法,調用順序是咋樣的呢?
鑒于上述幾節我們看的代碼太多了,對于這兩個問題我們先來看一點直觀的:
我們的代碼里有MyClass和MyClass的兩個category (Category1和Category2),MyClass和兩個category都添加了+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。ok,我們可以看到控制臺的輸出順序變了:
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其實并不是完全替換掉原來類的同名方法,只是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添加實例變量的。但是我們很多時候需要在category中添加和對象關聯的值,這個時候可以求助關聯對象來實現。
MyClass+Category1.h:
#import "MyClass.h"
@interface MyClass (Category1)
@property(nonatomic,copy) NSString *name;
@end
MyClass+Category1.m:
#import "MyClass+Category1.h"
#import <objc/runtime.h>
@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管理,而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是這個對象的指針地址(任意兩個不同對象的指針地址一定是不同的),而這個map的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卻是完全開放源碼的(在http://www.opensource.apple.com/tarballs/可以下載到全部的開源代碼)。%E3%80%82)
本系列runtime源碼學習將會持續更新,意猶未盡的同學可以自行到上述網站下載源碼學習。行筆簡陋,如有錯誤,望指正。
發現文章有錯誤、對內容有疑問,都可以關注美團技術團隊微信公眾號(meituantech),在后臺給我們留言。我們每周會挑選出一位熱心小伙伴,送上一份精美的小禮品。快來掃碼關注我們吧!