- Category編譯后,其本質(zhì)是結(jié)構(gòu)體struct _category_t,里面存儲著對象方法、類方法、屬性、協(xié)議等信息
- 程序運行時,runtime會將Category的數(shù)據(jù)合并到對應(yīng)的類(類對象、元類對象)中
- 調(diào)用順序:如果多個category中的方法同名,將調(diào)用后編譯的category中的方法。如果category和類中的方法同名,調(diào)用category中的方法。
struct _category_t
Category其實就是結(jié)構(gòu)體,我們可以在終端中運行以下命令
xcrun -sdk iphones clang -arch arm64 -rewrite-objc <OC源文件> -o <輸出文件.cpp>
通過將OC代碼轉(zhuǎn)換為C\C++代碼來證明。
創(chuàng)建一個ZJSPerson類的Category,
@implementation ZJSPerson (Test)
-(void)test{
NSLog(@"ZJSPerson (Test) test");
}
@end
在終端輸入xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc ./ZJSPerson+Test.m -o test.cpp,打開輸出的test.cpp文件,搜索_category_t就可以找到以下兩段代碼,分別是_category_t的定義,以及根據(jù)源文件初始化了一個名為_OBJC_$_CATEGORY_ZJSPerson_$_Test結(jié)構(gòu)體 。
struct _category_t {
const char *name;
struct _class_t *cls;
const struct _method_list_t *instance_methods;
const struct _method_list_t *class_methods;
const struct _protocol_list_t *protocols;
const struct _prop_list_t *properties;
};
// 初始化_category_t的一個實例
static struct _category_t _OBJC_$_CATEGORY_ZJSPerson_$_Test __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"ZJSPerson",
0, // &OBJC_CLASS_$_ZJSPerson,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_ZJSPerson_$_Test,
0,
0,
0,
};
由于ZJSPerson (Test)中只有一個實例方法,所以在初始化的時候除了類名字,只有 instance_methods有值,其他傳的都是0。
接下來我們再來看一下一個稍微復(fù)雜一點的Category,其中包含了實例方法、類方法、屬性、協(xié)議。
// ZJSPerson+Test2.h
@interface ZJSPerson (Test2)<NSCopying>
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *name;
@end
#import "ZJSPerson+Test2.h"
@implementation ZJSPerson (Test2)
- (void)setAge:(NSInteger)age{}
- (NSInteger)age{
return 0;
}
-(void)setName:(NSString *)name{
}
- (NSString *)name{
return nil;
}
- (void)run{}
- (void)eat{}
+ (void)test1{}
+ (void)test2{}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
return nil;
}
@end
將其轉(zhuǎn)化為cpp文件后,還是搜索_category_t,就可以找到_category_t的定義,以及初始化這個Category實例的地方。
static struct _category_t _OBJC_$_CATEGORY_ZJSPerson_$_Test2 __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"ZJSPerson",
0, // &OBJC_CLASS_$_ZJSPerson,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_ZJSPerson_$_Test2,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_CLASS_METHODS_ZJSPerson_$_Test2,
(const struct _protocol_list_t *)&_OBJC_CATEGORY_PROTOCOLS_$_ZJSPerson_$_Test2,
(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_ZJSPerson_$_Test2,
};
可以看到這次實例的名字變?yōu)榱?code>_OBJC_$_CATEGORY_ZJSPerson_$_Test2,初始化它的參數(shù)也變多了。
具體的參數(shù)詳情在cpp文件中也都可以看到。
例如下面的就是實例方法列表
static struct /*_method_list_t*/ {
unsigned int entsize; // sizeof(struct _objc_method)
unsigned int method_count;
struct _objc_method method_list[7];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_ZJSPerson_$_Test2 __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_objc_method),
7,
{{(struct objc_selector *)"setAge:", "v24@0:8q16", (void *)_I_ZJSPerson_Test2_setAge_},
{(struct objc_selector *)"age", "q16@0:8", (void *)_I_ZJSPerson_Test2_age},
{(struct objc_selector *)"setName:", "v24@0:8@16", (void *)_I_ZJSPerson_Test2_setName_},
{(struct objc_selector *)"name", "@16@0:8", (void *)_I_ZJSPerson_Test2_name},
{(struct objc_selector *)"run", "v16@0:8", (void *)_I_ZJSPerson_Test2_run},
{(struct objc_selector *)"eat", "v16@0:8", (void *)_I_ZJSPerson_Test2_eat},
{(struct objc_selector *)"copyWithZone:", "@24@0:8^{_NSZone=}16", (void *)_I_ZJSPerson_Test2_copyWithZone_}}
};
由此課件Category的本質(zhì)就是一個結(jié)構(gòu)體struct _category_t。每一個Category都是它的一個實例,存儲著對象方法、類方法、屬性、協(xié)議等信息。
runtime將Category合并到對應(yīng)的類
我們可以通過查看源碼來了解runtime是如何將Category合并到對應(yīng)的類。由于源碼版本較多,我下載的是此時最新的版本objc4-781.tar.gz,不同版本可能存在一些差異。
下面是源碼查看的順序
objc-os.mm
- void _objc_init(void)
objc-runtime-new.mm
- map_images
- _read_images(Called by: map_images_nolock)
- realizeClassWithoutSwift
- methodizeClass
- attachToClass
- attachCategories
- attachLists
為了便于理解主要看attachCategories和attachLists這兩個方法。
有下面的兩個方法課件,所有category方法的會組成一個二維數(shù)組,然后將這個數(shù)組添加到類的方法列表當中。
數(shù)組的順序是類自身的方法在最后面,后加載(編譯)的category在前,所以調(diào)用方法的時候先調(diào)用最后加載的category中的方法。如果category中的方法和類中的重復(fù),則將調(diào)用category中的方法
// 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, const locstamped_category_t *cats_list, uint32_t cats_count,
int flags)
{
if (slowpath(PrintReplacedMethods)) {
printReplacements(cls, cats_list, cats_count);
}
if (slowpath(PrintConnecting)) {
_objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
}
/*
* Only a few classes have more than 64 categories during launch.
* This uses a little stack, and avoids malloc.
*
* Categories must be added in the proper order, which is back
* to front. To do that with the chunking, we iterate cats_list
* from front to back, build up the local buffers backwards,
* and call attachLists on the chunks. attachLists prepends the
* lists, so the final result is in the expected order.
*/
constexpr uint32_t ATTACH_BUFSIZ = 64;
// 數(shù)組,每個元素保存了一個category中的所有方法,相當于二維數(shù)組
method_list_t *mlists[ATTACH_BUFSIZ];
// 數(shù)組,每個元素保存了一個category中的所有屬性,相當于二維數(shù)組
property_list_t *proplists[ATTACH_BUFSIZ];
// 數(shù)組,每個元素保存了一個保存category中的所有協(xié)議,相當于二維數(shù)組
protocol_list_t *protolists[ATTACH_BUFSIZ];
uint32_t mcount = 0;
uint32_t propcount = 0;
uint32_t protocount = 0;
bool fromBundle = NO;
bool isMeta = (flags & ATTACH_METACLASS);
auto rwe = cls->data()->extAllocIfNeeded();
for (uint32_t i = 0; i < cats_count; i++) {
auto& entry = cats_list[i];
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
if (mcount == ATTACH_BUFSIZ) {
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
// 如果category的數(shù)量超過了 ATTACH_BUFSIZ 這個容量,則先添加一部分
rwe->methods.attachLists(mlists, mcount);
mcount = 0;
}
// 從后向前,填充數(shù)組,先編譯的在后,后編譯的在前
mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
if (propcount == ATTACH_BUFSIZ) {
rwe->properties.attachLists(proplists, propcount);
propcount = 0;
}
proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
}
protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
if (protolist) {
if (protocount == ATTACH_BUFSIZ) {
rwe->protocols.attachLists(protolists, protocount);
protocount = 0;
}
protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
}
}
if (mcount > 0) {
// 添加剩余的category到類中
prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount, NO, fromBundle);
rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
if (flags & ATTACH_EXISTING) flushCaches(cls);
}
rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
// 將保存了category方法的二維數(shù)組,添加到類的方法列表當中
// 類自身的方法在最后面,后加載的category在前,所以調(diào)用方法的時候先調(diào)用最后加載的category中的方法
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;
// 重新申請內(nèi)存
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
array()->count = newCount;
// 將原來的數(shù)據(jù)(類自身的方法)移動到最后
memmove(array()->lists + addedCount, array()->lists,
oldCount * sizeof(array()->lists[0]));
// 將保存了category方法的二維數(shù)組,添加到類的方法列表當中
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]));
}
}