深入理解Objective-C:Category(上)
鏈接:http://tech.meituan.com/DiveIntoCategory.html
摘要
無論一個類設計的多么完美,在未來的需求演進中,都有可能會碰到一些無法預測的情況。那怎么擴展已有的類呢?一般而言,繼承和組合是不錯的選擇。但是在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
@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方法的結尾,有以下的代碼片段:
? ?for (EACH_HEADER) {
? ? ? ?category_t **catlist =
? ? ? ? ? ?_getObjc2CategoryList(hi, &count);
? ? ? ?for (i = 0; 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);
}
?