這篇文章介紹分類category、load、initialize的本質(zhì),并分析其源碼。
1. 分類 category
隨著需求的演進,類會遇到一些無法處理的情況,應如何擴展已有的類呢?
通常,繼承和組合是不錯的選擇。但 Objective-C 2.0 中,提供的分類category新特性,可以動態(tài)的為已有類添加新行為。Category 有以下幾個用途:
- 為已有的類添加新行為。此時,無需原來類的源碼,也無需繼承原來的類。例如,為 Cocoa Touch framework添加分類方法。添加的分類方法會被子類繼承,在運行時和原始方法沒有區(qū)別。
- 把類的實現(xiàn)根據(jù)功能劃分到不同文件。
- 聲明私有方法。
1.1 聲明、實現(xiàn)一個分類
分類的聲明和類的聲明類似,但有以下幾點不同:
- 分類名稱寫在類名稱后的圓括號內(nèi)。
- 不需要說明父類。
- 必須導入分類擴展的類。
為Child
類添加一個分類,如下所示:
#import "Child.h"
NS_ASSUME_NONNULL_BEGIN
@interface Child (Test1)
@property (nonatomic, strong) NSString *title;
- (void)test;
@end
NS_ASSUME_NONNULL_END
#import "Child+Test1.h"
@implementation Child (Test1)
- (void)test {
NSLog(@"%d %s", __LINE__, __PRETTY_FUNCTION__);
}
- (void)run {
NSLog(@"%d %s", __LINE__, __PRETTY_FUNCTION__);
}
@end
分類文件名稱一般為:類名稱+分類名稱,即Child+Test1
模式。
如果想使用分類為自己的類添加私有方法,可以把分類的聲明放到類實現(xiàn)文件的
@implementation
前。
1.2 調(diào)用分類方法
在Runtime從入門到進階一中,介紹了runtime的消息發(fā)送機制:
調(diào)用對象方法時,根據(jù)實例對象的isa查找到類對象,在類對象的方法列表中查找方法,找到后直接調(diào)用;如果找不到,則根據(jù)superclass指針,進入父類查找。找到后直接調(diào)用;如果找不到,則繼續(xù)向父類查找。以此類推,直到找到方法,或拋出doesNotRecognizeSelector:
異常。
為上面的Child
類繼續(xù)添加Child+Test2
分類,Child
、Child+Test1
、Child+Test2
都實現(xiàn)了test
方法。使用以下代碼調(diào)用test
方法,看最終調(diào)用哪個test
方法。
Child *child = [[Child alloc] init];
[child test];
執(zhí)行后控制臺打印如下:
13 -[Child(Test2) test]
即調(diào)用了分類的test
方法。事實上,類、分類實現(xiàn)了同一方法時,總是優(yōu)先調(diào)用分類的方法。一個類的多個分類實現(xiàn)了同一方法時,后編譯的優(yōu)先調(diào)用,后續(xù)會介紹這一現(xiàn)象的本質(zhì)原因。
類根據(jù) Xcode 中Build Phases > Compile Sources 文件順序進行編譯,自上而下依次編譯:
你可以手動拖動文件,改變其編譯順序。拖動后,再次執(zhí)行上述代碼,看控制臺輸出是否發(fā)生了改變。
1.3 分類的底層結構
分類的方法不是在編譯期合并到原來類中的,而是在運行時合并進去的。
使用clang
命令可以將 Objective-C 的代碼轉(zhuǎn)換為 C++,方便查看其底層實現(xiàn),命令如下:
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc <objc文件名稱.m> -o <輸出文件名稱.cpp>
將Child+Test1.m
轉(zhuǎn)換為Child+Test1.cpp
文件命令如下:
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc Child+Test1.m -o Child+Test1.cpp
生成的Child+Test1.cpp
文件有三萬四千行,滑到底部可以看到 category 的數(shù)據(jù)結構:
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; // 分類協(xié)議列表
const struct _prop_list_t *properties; // 分類屬性列表
};
繼續(xù)向下查找,可以看到對象方法列表如下:
static struct /*_method_list_t*/ {
unsigned int entsize; // sizeof(struct _objc_method)
unsigned int method_count;
struct _objc_method method_list[2];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_Child_$_Test1 __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_objc_method),
2,
{{(struct objc_selector *)"test", "v16@0:8", (void *)_I_Child_Test1_test},
{(struct objc_selector *)"run", "v16@0:8", (void *)_I_Child_Test1_run}}
};
它包含了test
和run
兩個方法。
為Child+Test2
類添加添加NSCoding
、NSCoping
協(xié)議和其他類方法。再次使用clang命令將其轉(zhuǎn)換為C++。可以看到其中的協(xié)議列表、類方法列表增加了相應的內(nèi)容。如下所示:
static struct /*_protocol_list_t*/ {
long protocol_count; // Note, this is 32/64 bit
struct _protocol_t *super_protocols[2];
} _OBJC_CATEGORY_PROTOCOLS_$_Child_$_Test2 __attribute__ ((used, section ("__DATA,__objc_const"))) = { // 協(xié)議
2,
&_OBJC_PROTOCOL_NSCoding,
&_OBJC_PROTOCOL_NSCopying
};
1.4 分類category_t結構
這里使用的是objc4最新源碼objc4-818.2。在源碼中,category結構體如下:
struct category_t {
const char *name; // 類名
classref_t cls;
WrappedPtr<method_list_t, PtrauthStrip> instanceMethods; // 實例方法列表
WrappedPtr<method_list_t, PtrauthStrip> classMethods; // 類方法列表
struct protocol_list_t *protocols; // 協(xié)議列表
struct property_list_t *instanceProperties; // 屬性列表
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties;
method_list_t *methodsForMeta(bool isMeta) {
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
protocol_list_t *protocolsForMeta(bool isMeta) {
if (isMeta) return nullptr;
else return protocols;
}
};
通過源碼可以看到,分類中有實例方法列表、類方法列表、協(xié)議列表、屬性列表,但沒有成員變量列表。因此,分類中是不能添加成員變量的。分類中添加的屬性并不會自動生成成員變量,只會生成get、set方法的聲明,需要開發(fā)者自行實現(xiàn)訪問器方法。
通過源碼看到,category的實例方法、類方法、協(xié)議、屬性存放在category_t
結構體中。目前,分類里的信息和類里的信息是分開存儲的。
那么是如何合并到原來類中的?
1.5 分類信息合并到類源碼
程序一運行,就會把所有類對象、類對象信息、元類等,加載到內(nèi)存中。
RunTime 的入口在objc-os.mm
文件的_objc_init()
方法中:
/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/
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();
runtime_init();
exception_init();
#if __OBJC2__
cache_t::init();
#endif
_imp_implementationWithBlock_init();
// image是模塊、鏡像,并非圖片。
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
#if __OBJC2__
didCallDyldNotifyRegister = true;
#endif
}
map_images()
會調(diào)用map_images_nolock()
函數(shù),map_images_nolock()
會調(diào)用_read_images()
函數(shù),_read_images()
函數(shù)如下:
/***********************************************************************
* _read_images
* Perform initial processing of the headers in the linked
* list beginning with headerList.
*
* Called by: map_images_nolock
*
* Locking: runtimeLock acquired by map_images
**********************************************************************/
void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{
// 省略部分...
// 分類
// Discover categories. Only do this after the initial category
// attachment has been done. For categories present at startup,
// discovery is deferred until the first load_images call after
// the call to _dyld_objc_notify_register completes. rdar://problem/53119145
if (didInitialAttachCategories) {
for (EACH_HEADER) {
// 加載分類
load_categories_nolock(hi);
}
}
ts.log("IMAGE TIMES: discover categories");
// Category discovery MUST BE Late to avoid potential races
// when other threads call the new category code before
// this thread finishes its fixups.
// +load handled by prepare_load_methods()
// 省略部分...
}
#undef EACH_HEADER
}
這里調(diào)用了load_categories_nolock()
函數(shù):
static void load_categories_nolock(header_info *hi) {
bool hasClassProperties = hi->info()->hasCategoryClassProperties();
size_t count;
auto processCatlist = [&](category_t * const *catlist) {
for (unsigned i = 0; i < count; i++) {
category_t *cat = catlist[I];
Class cls = remapClass(cat->cls);
locstamped_category_t lc{cat, hi};
if (!cls) {
// Category's target class is missing (probably weak-linked).
// Ignore the category.
if (PrintConnecting) {
_objc_inform("CLASS: IGNORING category \?\?\?(%s) %p with "
"missing weak-linked target class",
cat->name, cat);
}
continue;
}
// Process this category.
if (cls->isStubClass()) {
// Stub classes are never realized. Stub classes
// don't know their metaclass until they're
// initialized, so we have to add categories with
// class methods or properties to the stub itself.
// methodizeClass() will find them and add them to
// the metaclass as appropriate.
if (cat->instanceMethods ||
cat->protocols ||
cat->instanceProperties ||
cat->classMethods ||
cat->protocols ||
(hasClassProperties && cat->_classProperties))
{
objc::unattachedCategories.addForClass(lc, cls);
}
} else {
// First, register the category with its target class.
// Then, rebuild the class's method lists (etc) if
// the class is realized.
// 先向類注冊分類,再重建類的方法列表。
if (cat->instanceMethods || cat->protocols
|| cat->instanceProperties)
{
if (cls->isRealized()) {
// 附加分類
attachCategories(cls, &lc, 1, ATTACH_EXISTING);
} else {
objc::unattachedCategories.addForClass(lc, cls);
}
}
if (cat->classMethods || cat->protocols
|| (hasClassProperties && cat->_classProperties))
{
if (cls->ISA()->isRealized()) {
// 附加分類
attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
} else {
objc::unattachedCategories.addForClass(lc, cls->ISA());
}
}
}
}
};
processCatlist(hi->catlist(&count));
processCatlist(hi->catlist2(&count));
}
其中調(diào)用attachCategories()
函數(shù),將分類的的實例方法、協(xié)議、屬性、類方法合并到類中。attachCategories()
函數(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, 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ù)組
method_list_t *mlists[ATTACH_BUFSIZ];
// 屬性數(shù)組
property_list_t *proplists[ATTACH_BUFSIZ];
// 協(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, __func__);
rwe->methods.attachLists(mlists, mcount);
mcount = 0;
}
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) {
prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
NO, fromBundle, __func__);
// 將所有分類的對象方法,附加到類對象的方法列表中。
rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
if (flags & ATTACH_EXISTING) {
flushCaches(cls, __func__, [](Class c){
// constant caches have been dealt with in prepareMethodLists
// if the class still is constant here, it's fine to keep
return !c->cache.isConstantOptimizedCache();
});
}
}
// 將所有分類的屬性,附加到類對象的屬性列表中。
rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
// 將所有分類的協(xié)議,附加到類對象的協(xié)議中。
rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
上述函數(shù)調(diào)用了attachLists()
函數(shù),attachLists()
函數(shù)如下:
/*
addedLists是二維數(shù)組
[
[method_t, method_t]
[method_t, method_t]
]
addedCount是分類數(shù)量
*/
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;
array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
newArray->count = newCount;
array()->count = newCount;
for (int i = oldCount - 1; i >= 0; I--)
// array()->lists是原來的方法列表
newArray->lists[i + addedCount] = array()->lists[I];
// addedLists是所有分類的方法列表,把分類方法列表放到方法列表前面。
for (unsigned i = 0; i < addedCount; I++)
newArray->lists[i] = addedLists[I];
free(array());
setArray(newArray);
validate();
}
else if (!list && addedCount == 1) {
// 0 lists -> 1 list
list = addedLists[0];
validate();
}
else {
// 1 list -> many lists
Ptr<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;
for (unsigned i = 0; i < addedCount; I++)
array()->lists[i] = addedLists[I];
validate();
}
}
可以看到,合并時先將原來類中的方法向后移動,再將分類方法放到方法列表前面。因此,進行方法查找時,先找到分類方法,找到后不再查找,這就形成了分類方法會覆蓋類方法的錯覺。
事實上,如果分類和原來類都有同樣方法時,category附加完成后方法列表會有兩個相同的方法,只是分類方法位于列表前面,優(yōu)先查找到分類方法。
分類的方法列表和類的實例方法一樣,最終放在同一個類對象的方法列表,并不會存放在單獨的方法列表中。類方法、協(xié)議、屬性等類似。
2. load方法
多數(shù)情況下,開發(fā)者無需關心 Objective-C 中的類是如何加載進內(nèi)存的,這一復雜過程由 runtime 的 linker 處理,并且會在你的代碼開始執(zhí)行前處理完成。
多數(shù)類無需關心類加載過程,但有時可能需要初始化全局表、用戶數(shù)據(jù)緩存等任務。
Objective-C runtime 提供了+load
、+initialize
兩個方法,用于解決上述問題。
2.1 介紹
如果實現(xiàn)了+load
方法,其會在加載類時被調(diào)用。+load
只會調(diào)用一次,并且是在調(diào)用main()
函數(shù)前調(diào)用。如果在可加載的 bundle 實現(xiàn)了+load
方法,他會在 bundle 加載過程中調(diào)用。
因為+load
被調(diào)用的時機太早了,可能產(chǎn)生一些很奇怪的問題。例如,在+load
方法中使用其他類時,無法確定其他類是否已經(jīng)加載了;C++ 中的 static initializer 此階段還沒有執(zhí)行,如果你依賴了其中的方法會導致閃退。但 framework 中的類已經(jīng)加載完畢,你可以使用 framework 中的類。父類已經(jīng)加載完成,可以安全使用。
2.2 使用
通過代碼驗證一下+load
方法的調(diào)用。
創(chuàng)建Person
類,繼承自NSObject
,創(chuàng)建Person
的兩個分類Person+Test1
、Person+Test2
。創(chuàng)建繼承自Person
的Student
類,創(chuàng)建Student
的兩個分類Student+Test1
、Student+Test2
。所有類、分類都實現(xiàn)+load
方法,如下所示:
+ (void)load {
NSLog(@"%d %s", __LINE__, __PRETTY_FUNCTION__);
}
多次執(zhí)行后,控制臺總是先打印Person
的+load
方法,后打印Student
的+load
方法,最后根據(jù)編譯順序打印分類+load
方法。拖動Build Phases > Compile Sources文件順序,可以修改編譯順序。
2.3 源碼分析
RunTime 入口函數(shù)_objc_init()
的load_images()
函數(shù)開始調(diào)用+load
方法。
void
load_images(const char *path __unused, const struct mach_header *mh)
{
if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
didInitialAttachCategories = true;
loadAllCategories();
}
// Return without taking locks if there are no +load methods here.
if (!hasLoadMethods((const headerType *)mh)) return;
recursive_mutex_locker_t lock(loadMethodLock);
// Discover load methods
{
mutex_locker_t lock2(runtimeLock);
// 先調(diào)用
prepare_load_methods((const headerType *)mh);
}
// Call +load methods (without runtimeLock - re-entrant)
// 后調(diào)用
call_load_methods();
}
call_load_methods()
函數(shù)先調(diào)用父類的+load
,等父類的+load
結束后才會調(diào)用分類的+load
方法。如下所示:
/***********************************************************************
* call_load_methods
* Call all pending class and category +load methods.
* Class +load methods are called superclass-first.
* Category +load methods are not called until after the parent class's +load.
*
* This method must be RE-ENTRANT, because a +load could trigger
* more image mapping. In addition, the superclass-first ordering
* must be preserved in the face of re-entrant calls. Therefore,
* only the OUTERMOST call of this function will do anything, and
* that call will handle all loadable classes, even those generated
* while it was running.
*
* The sequence below preserves +load ordering in the face of
* image loading during a +load, and make sure that no
* +load method is forgotten because it was added during
* a +load call.
* Sequence:
* 1. Repeatedly call class +loads until there aren't any more
* 2. Call category +loads ONCE.
* 3. Run more +loads if:
* (a) there are more classes to load, OR
* (b) there are some potential category +loads that have
* still never been attempted.
* Category +loads are only run once to ensure "parent class first"
* ordering, even if a category +load triggers a new loadable class
* and a new loadable category attached to that class.
*
* Locking: loadMethodLock must be held by the caller
* All other locks must not be held.
**********************************************************************/
void call_load_methods(void)
{
static bool loading = NO;
bool more_categories;
loadMethodLock.assertLocked();
// Re-entrant calls do nothing; the outermost call will finish the job.
if (loading) return;
loading = YES;
void *pool = objc_autoreleasePoolPush();
do {
// 1. Repeatedly call class +loads until there aren't any more
while (loadable_classes_used > 0) {
// 先調(diào)用class的load方法
call_class_loads();
}
// 2. Call category +loads ONCE
// 后調(diào)用分類的load方法
more_categories = call_category_loads();
// 3. Run more +loads if there are classes OR more untried categories
} while (loadable_classes_used > 0 || more_categories);
objc_autoreleasePoolPop(pool);
loading = NO;
}
call_class_loads()
函數(shù)調(diào)用所有掛起類的+load
方法。如果有新的類變?yōu)榭杉虞d,并不會調(diào)用他們的+load
方法。找到+load
方法函數(shù)地址后,直接調(diào)用。如下所示:
/***********************************************************************
* call_class_loads
* Call all pending class +load methods.
* If new classes become loadable, +load is NOT called for them.
*
* Called only by call_load_methods().
**********************************************************************/
static void call_class_loads(void)
{
int I;
// Detach current loadable list.
struct loadable_class *classes = loadable_classes;
int used = loadable_classes_used;
loadable_classes = nil;
loadable_classes_allocated = 0;
loadable_classes_used = 0;
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
Class cls = classes[i].cls;
// 得到load方法的函數(shù)地址
load_method_t load_method = (load_method_t)classes[i].method;
if (!cls) continue;
if (PrintLoading) {
_objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
}
// 直接調(diào)用load方法
(*load_method)(cls, @selector(load));
}
// Destroy the detached list.
if (classes) free(classes);
}
調(diào)用分類的+load
方法與調(diào)用類的+load
方法類似,也是通過函數(shù)指針直接指向函數(shù),拿到函數(shù)地址,找到函數(shù)直接調(diào)用。如下所示:
/***********************************************************************
* call_category_loads
* Call some pending category +load methods.
* The parent class of the +load-implementing categories has all of
* its categories attached, in case some are lazily waiting for +initalize.
* Don't call +load unless the parent class is connected.
* If new categories become loadable, +load is NOT called, and they
* are added to the end of the loadable list, and we return TRUE.
* Return FALSE if no new categories became loadable.
*
* Called only by call_load_methods().
**********************************************************************/
static bool call_category_loads(void)
{
int i, shift;
bool new_categories_added = NO;
// Detach current loadable list.
struct loadable_category *cats = loadable_categories;
int used = loadable_categories_used;
int allocated = loadable_categories_allocated;
loadable_categories = nil;
loadable_categories_allocated = 0;
loadable_categories_used = 0;
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
Category cat = cats[i].cat;
// 獲取分類的load方法地址
load_method_t load_method = (load_method_t)cats[i].method;
Class cls;
if (!cat) continue;
cls = _category_getClass(cat);
if (cls && cls->isLoadable()) {
if (PrintLoading) {
_objc_inform("LOAD: +[%s(%s) load]\n",
cls->nameForLogging(),
_category_getName(cat));
}
// 調(diào)用分類的load方法
(*load_method)(cls, @selector(load));
cats[i].cat = nil;
}
}
// 省略...
}
loadable_class
和loadable_category
結構體如下:
struct loadable_class {
Class cls; // may be nil
IMP method; // 函數(shù)實現(xiàn)地址,指向類的load方法。
};
struct loadable_category {
Category cat; // may be nil
IMP method; // 函數(shù)實現(xiàn)地址,指向分類的load方法
};
Runtime的消息機制需要通過
isa
指針查找類對象、元類對象,進一步在方法列表中查找方法。+load
方法的調(diào)用不是通過消息機制進行的,而是直接找到函數(shù)指針,拿到函數(shù)地址,直接調(diào)用函數(shù)。因此,類、分類同時實現(xiàn)了+load
方法時,都會被調(diào)用。但如果使用[Person load]
方式調(diào)用+load
方法,則會使用消息機制進行調(diào)用。此時,分類的+load
方法會被優(yōu)先調(diào)用。
通過源碼的call_class_loads()
、call_category_loads()
函數(shù),可以看到調(diào)用類、分類+load
方法時,都是通過for
循環(huán)loadable_classes
、loadable_categories
數(shù)組進行的。因此,知道數(shù)組的順序,就可以知道方法調(diào)用順序。
load_images()
函數(shù)在調(diào)用call_load_methods()
函數(shù)前調(diào)用了prepare_load_methods()
方法。prepare_load_methods()
方法會把類、分類添加到相應數(shù)組:
void prepare_load_methods(const headerType *mhdr)
{
size_t count, I;
runtimeLock.assertLocked();
classref_t const *classlist =
_getObjc2NonlazyClassList(mhdr, &count);
for (i = 0; i < count; i++) {
// 將類、未加載的父類添加到loadable_classes數(shù)組。
schedule_class_load(remapClass(classlist[i]));
}
category_t * const *categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
for (i = 0; i < count; i++) {
category_t *cat = categorylist[I];
Class cls = remapClass(cat->cls);
if (!cls) continue; // category for ignored weak-linked class
if (cls->isSwiftStable()) {
_objc_fatal("Swift class extensions and categories on Swift "
"classes are not allowed to have +load methods");
}
realizeClassWithoutSwift(cls, nil);
ASSERT(cls->ISA()->isRealized());
// 將分類添加到loadable_categories數(shù)組
add_category_to_loadable_list(cat);
}
}
schedule_class_load()
會遞歸調(diào)用,確保先將未加載的父類添加到loadable_classes
數(shù)組。
/***********************************************************************
* prepare_load_methods
* Schedule +load for classes in this image, any un-+load-ed
* superclasses in other images, and any categories in this image.
**********************************************************************/
// Recursively schedule +load for cls and any un-+load-ed superclasses.
// cls must already be connected.
static void schedule_class_load(Class cls)
{
if (!cls) return;
ASSERT(cls->isRealized()); // _read_images should realize
if (cls->data()->flags & RW_LOADED) return;
// Ensure superclass-first ordering
// 遞歸調(diào)用,確保先將父類添加到loadable_classes數(shù)組。
schedule_class_load(cls->getSuperclass());
// 將類cls添加到loadable_classes數(shù)組
add_class_to_loadable_list(cls);
cls->setInfo(RW_LOADED);
}
如果類實現(xiàn)了+load
方法,add_class_to_loadable_list()
函數(shù)會將其添加到loadable_classes
數(shù)組,準備加載。
/***********************************************************************
* add_class_to_loadable_list
* Class cls has just become connected. Schedule it for +load if
* it implements a +load method.
**********************************************************************/
// 如果類實現(xiàn)了`+load`方法,add_class_to_loadable_list()函數(shù)會將其添加到loadable_classes數(shù)組,準備加載。
void add_class_to_loadable_list(Class cls)
{
IMP method;
loadMethodLock.assertLocked();
method = cls->getLoadMethod();
if (!method) return; // Don't bother if cls has no +load method
if (PrintLoading) {
_objc_inform("LOAD: class '%s' scheduled for +load",
cls->nameForLogging());
}
if (loadable_classes_used == loadable_classes_allocated) {
loadable_classes_allocated = loadable_classes_allocated*2 + 16;
loadable_classes = (struct loadable_class *)
realloc(loadable_classes,
loadable_classes_allocated *
sizeof(struct loadable_class));
}
loadable_classes[loadable_classes_used].cls = cls;
loadable_classes[loadable_classes_used].method = method;
loadable_classes_used++;
}
add_category_to_loadable_list()
函數(shù)將分類+load
方法添加到loadable_categories
數(shù)組:
/***********************************************************************
* add_category_to_loadable_list
* Category cat's parent class exists and the category has been attached
* to its class. Schedule this category for +load after its parent class
* becomes connected and has its own +load method called.
**********************************************************************/
// 將分類添加到loadable_categories數(shù)組
void add_category_to_loadable_list(Category cat)
{
IMP method;
loadMethodLock.assertLocked();
method = _category_getLoadMethod(cat);
// Don't bother if cat has no +load method
if (!method) return;
if (PrintLoading) {
_objc_inform("LOAD: category '%s(%s)' scheduled for +load",
_category_getClassName(cat), _category_getName(cat));
}
if (loadable_categories_used == loadable_categories_allocated) {
loadable_categories_allocated = loadable_categories_allocated*2 + 16;
loadable_categories = (struct loadable_category *)
realloc(loadable_categories,
loadable_categories_allocated *
sizeof(struct loadable_category));
}
loadable_categories[loadable_categories_used].cat = cat;
loadable_categories[loadable_categories_used].method = method;
loadable_categories_used++;
}
2.4 load方法總結
通過上述源碼可以發(fā)現(xiàn),數(shù)組的添加順序決定+load
方法調(diào)用順序。添加順序是:
- 先添加父類。
- 后添加類。
- 最后添加分類。如果有多個分類,先編譯的先添加,可手動設置編譯順序。
3. initialize方法
+initialize
方法是懶加載的,加載類時不會調(diào)用,首次向類發(fā)消息時才會調(diào)用。因此+initialize
方法可能不被調(diào)用。
將消息發(fā)送給類時,runtime先檢查是否調(diào)用了+initialize
。如果沒有調(diào)用,會在發(fā)消息之前調(diào)用。偽代碼如下:
id objc_msgSend(id self, SEL _cmd, ...) {
if(!self->class->initialized)
[self->class initialize];
...send the message...
}
實際情況可能比上述偽代碼復雜些,例如需考慮線程安全,但整體邏輯沒有變化。每個類的+initialize
方法只調(diào)用一次,發(fā)生在首次向其發(fā)送消息時。與+load
方法類似,如果父類的+initialize
沒有調(diào)用過,先調(diào)用父類的+initialize
,再調(diào)用該類的+initialize
方法。
與+load
方法相比,+initialize
更為安全。收到消息后才會調(diào)用+initialize
方法,其調(diào)用時機取決于消息發(fā)送,但肯定會晚于NSApplicationMain()
函數(shù)的調(diào)用。
由于調(diào)用+initialize
方法是懶加載的方式進行的,其不適合于注冊類。例如,NSValueTransformer
、NSURLProtocol
協(xié)議的子類不能使用+initialize
方法向父類注冊。因為,父類注冊完成才能調(diào)用子類,而子類想要在父類注冊前添加自身。
+initialize
適用于上述類型之外的任務。由于其他類已經(jīng)加載完成,你可以任意調(diào)用其他代碼。由于使用了懶加載,直到使用類時才執(zhí)行,不會浪費資源。
3.1 使用
為load部分創(chuàng)建的類添加+initialize
方法,此外創(chuàng)建繼承自NSObject
的Dog
、Cat
類,分別實現(xiàn)+initialize
方法:
+ (void)initialize {
NSLog(@"%d %s %@", __LINE__, __PRETTY_FUNCTION__, self);
}
使用以下代碼向類發(fā)送消息:
[Dog alloc];
[Cat alloc];
[Person alloc];
[Student alloc];
執(zhí)行后控制臺輸出如下:
13 +[Dog initialize] Dog
13 +[Cat initialize] Cat
17 +[Person(Test2) initialize] Person
17 +[Student(Test2) initialize] Student
雖然所有分類、類都實現(xiàn)了+initialize
方法,但只調(diào)用了分類的方法。因此,可以推測+initialize
的調(diào)用依賴消息機制,而非+load
的找到函數(shù)地址直接調(diào)用模式。
注釋掉Student
類、分類中的+initialize
方法,執(zhí)行后輸出如下:
13 +[Dog initialize] Dog
13 +[Cat initialize] Cat
17 +[Person(Test2) initialize] Person
17 +[Person(Test2) initialize] Student
可以看到Person+Test2
的+initialize
方法調(diào)用了兩次,第一次是Person
調(diào)用,第二次是Student
調(diào)用。因此,當子類沒有實現(xiàn)+initialize
方法時,會查找調(diào)用父類方法。與消息機制的查找模式一致。
因此,要避免類的+initialize
被多次調(diào)用,應使用以下方式編寫+initialize
代碼:
+ (void)initialize {
if (self == [ClassName self]) {
NSLog(@"%d %s %@", __LINE__, __PRETTY_FUNCTION__, self);
}
}
如果不添加上述判斷,子類沒有重寫+initialize
方法會導致父類的該方法被調(diào)用多次。即使你的類沒有子類,也應添加上述判斷,因為 Apple 的 Key-Value-Observing 會動態(tài)創(chuàng)建子類,但不會重寫+initialize
方法。因此,添加觀察者后,也會導致+initialize
被調(diào)用多次。
3.2 源碼分析
class_getInstanceMethod()
用來查找實例方法,class_getClassMethod()
通過調(diào)用class_getInstanceMethod()
來查找類方法:
/***********************************************************************
* class_getClassMethod. Return the class method for the specified
* class and selector.
**********************************************************************/
Method class_getClassMethod(Class cls, SEL sel)
{
if (!cls || !sel) return nil;
return class_getInstanceMethod(cls->getMeta(), sel);
}
class_getInstanceMethod()
函數(shù)用來搜索方法:
/***********************************************************************
* class_getInstanceMethod. Return the instance method for the
* specified class and selector.
**********************************************************************/
Method class_getInstanceMethod(Class cls, SEL sel)
{
if (!cls || !sel) return nil;
// This deliberately avoids +initialize because it historically did so.
// This implementation is a bit weird because it's the only place that
// wants a Method instead of an IMP.
#warning fixme build and search caches
// Search method lists, try method resolver, etc.
// 搜索方法
lookUpImpOrForward(nil, sel, cls, LOOKUP_RESOLVER);
#warning fixme build and search caches
return _class_getMethod(cls, sel);
}
lookUpImpOrForward()
函數(shù)調(diào)用了realizeAndInitializeIfNeeded_locked()
函數(shù),realizeAndInitializeIfNeeded_locked()
函數(shù)調(diào)用了realizeAndInitializeIfNeeded_locked()
函數(shù),realizeAndInitializeIfNeeded_locked()
函數(shù)調(diào)用了initializeAndLeaveLocked()
函數(shù),initializeAndLeaveLocked()
函數(shù)調(diào)用了initializeAndMaybeRelock()
函數(shù),initializeAndMaybeRelock()
函數(shù)調(diào)用了initializeNonMetaClass()
函數(shù)。
initializeNonMetaClass()
函數(shù)會查看父類是否已經(jīng)調(diào)用過+initialize
方法,如果父類沒有調(diào)用過,遞歸調(diào)用,先讓父類調(diào)用+initialize
方法。如下所示:
/***********************************************************************
* class_initialize. Send the '+initialize' message on demand to any
* uninitialized class. Force initialization of superclasses first.
**********************************************************************/
void initializeNonMetaClass(Class cls)
{
ASSERT(!cls->isMetaClass());
Class supercls;
bool reallyInitialize = NO;
// Make sure super is done initializing BEFORE beginning to initialize cls.
// See note about deadlock above.
supercls = cls->getSuperclass();
if (supercls && !supercls->isInitialized()) {
// 如果父類沒有調(diào)用過 initialize,遞歸調(diào)用父類的。
initializeNonMetaClass(supercls);
}
// Try to atomically set CLS_INITIALIZING.
SmallVector<_objc_willInitializeClassCallback, 1> localWillInitializeFuncs;
{
monitor_locker_t lock(classInitLock);
if (!cls->isInitialized() && !cls->isInitializing()) {
cls->setInitializing();
reallyInitialize = YES;
// Grab a copy of the will-initialize funcs with the lock held.
localWillInitializeFuncs.initFrom(willInitializeFuncs);
}
}
if (reallyInitialize) {
// We successfully set the CLS_INITIALIZING bit. Initialize the class.
// Record that we're initializing this class so we can message it.
_setThisThreadIsInitializingClass(cls);
if (MultithreadedForkChild) {
// LOL JK we don't really call +initialize methods after fork().
performForkChildInitialize(cls, supercls);
return;
}
for (auto callback : localWillInitializeFuncs)
callback.f(callback.context, cls);
// Send the +initialize message.
// Note that +initialize is sent to the superclass (again) if
// this class doesn't implement +initialize. 2157218
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: calling +[%s initialize]",
objc_thread_self(), cls->nameForLogging());
}
// Exceptions: A +initialize call that throws an exception
// is deemed to be a complete and successful +initialize.
//
// Only __OBJC2__ adds these handlers. !__OBJC2__ has a
// bootstrapping problem of this versus CF's call to
// objc_exception_set_functions().
#if __OBJC2__
@try
#endif
{
// 調(diào)用initialize方法。
callInitialize(cls);
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
objc_thread_self(), cls->nameForLogging());
}
}
#if __OBJC2__
@catch (...) {
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: +[%s initialize] "
"threw an exception",
objc_thread_self(), cls->nameForLogging());
}
@throw;
}
// 省略...
}
initializeNonMetaClass()
函數(shù)調(diào)用了callInitialize()
函數(shù),callInitialize()
函數(shù)如下所示:
// 使用消息機制,調(diào)用initialize
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, @selector(initialize));
asm("");
}
可以看到,callInitialize
最終使用objc_msgSend
調(diào)用了@selector(initialize)
。至此,整個調(diào)用結束。
Runtime向類發(fā)送initialize
消息是線程安全的,即首個向類發(fā)送消息的線程執(zhí)行initialize
,其他線程會堵塞等待initialize
完成。
4. 面試題
4.1 Category的實現(xiàn)原理?
Category編譯之后底層結構是struct category_t
,里面存儲著分類的對象方法、類方法、屬性、協(xié)議信息。程序運行的時候,runtime將category的數(shù)據(jù)合并到類信息中,并且分類信息位于類信息前面。分類方法是后編譯的優(yōu)先調(diào)用。
4.2 Category和Class Extension區(qū)別是什么?
Class Extension 在編譯的時候?qū)?shù)據(jù)合并到類信息中。想要添加 Class Extension,必須擁有類的源碼。
Category 在運行時將數(shù)據(jù)合并到類信息中,可以為系統(tǒng) framework、第三方框架等添加 category。
4.3 Category中有+load
方法嗎?+load
方法是什么時候調(diào)用的?+load
方法能繼承嗎?
Category
中有+load
方法。
程序加載類、分類的時候調(diào)用+load
方法,在main
函數(shù)之前。
+load
方法可以繼承。調(diào)用子類的+load
方法之前,會先調(diào)用父類的+load
方法。一般不手動調(diào)用+load
方法,而是讓系統(tǒng)去調(diào)用。如果手動調(diào)用+load
方法,就會按照消息發(fā)送機制,通過isa
指針找到類、元類,之后在方法列表中進行查找。
4.4 load、initialize方法的區(qū)別?
- 調(diào)用方式:
- load根據(jù)函數(shù)地址直接調(diào)用。
- initialize通過
objc_msgSend
調(diào)用。
- 調(diào)用時機:
- load是runtime加載類、分類的時候調(diào)用,只會調(diào)用一次。
- initialize是類第一次接收消息時調(diào)用,每個類只會 initialize 一次,但父類的
+initialize
方法可能會被調(diào)用多次。
4.5 load、initialize調(diào)用順序?
- load
- 先調(diào)用類的load。
- 先編譯的類,優(yōu)先調(diào)用。
- 調(diào)用子類load前會先調(diào)用父類的load。
- 后調(diào)用分類的load。
- 先編譯的分類,優(yōu)先調(diào)用。
- 先調(diào)用類的load。
- initialize
- 先初始化父類。
- 后初始化子類。如果子類沒有實現(xiàn)
+initialize
方法,最終會調(diào)用父類的+initialize
方法。
總結
Objective-C 提供了兩種自動配置類的方法,類加載時調(diào)用+load
方法,對于需要讓代碼運行非常早的情景非常有用。但因為+load
方法調(diào)用太早,其他類可能未加載而產(chǎn)生危險。
+initialize
方法使用懶加載,首次收到消息時才會調(diào)用,適用場景更廣泛。
Demo名稱:category、load、initialize的本質(zhì)
源碼地址:https://github.com/pro648/BasicDemos-iOS/tree/master/category、load、initialize的本質(zhì)
參考資料:
- Objective-C Class Loading and Initialization
- Category
- Customizing Existing Classes
- 深入理解Objective-C:Category
歡迎更多指正:https://github.com/pro648/tips
本文地址:https://github.com/pro648/tips/blob/master/sources/分類category、load、initialize的本質(zhì)和源碼分析.md