本文屬筆記性質,主要針對本身理解不太透徹的地方進行記錄。ios
推薦系統直接學習小碼哥iOS底層原理班---MJ老師的課確實不錯,強推一波。bash
+load
方法會在runtime
加載類、分類時調用ide每一個類、分類的
+load
,在程序運行過程當中只調用一次函數調用順序學習
先調用類的
+load
ui按照編譯前後順序調用(先編譯,先調用)this
調用子類的
+load
以前會先調用父類的+load
spa再調用分類的
+load
ssr按照編譯前後順序調用(先編譯,先調用)指針
+initialize
方法會在類第一次接收到消息時調用調用順序
先調用父類的
+initialize
,再調用子類的+initialize
(先初始化父類,再初始化子類,每一個類只會初始化1次)
+initialize
和+load
的很大區別是,+initialize是經過objc_msgSend進行調用的,因此有如下特色
若是子類沒有實現
+initialize
,會調用父類的+initialize
(因此父類的+initialize
可能會被調用屢次)若是分類實現了
+initialize
,就覆蓋類自己的+initialize
調用
先調用類的+load,再調用分類的+load
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 {
/ **** 首先調用class的load方法 ***/
while (loadable_classes_used > 0) {
call_class_loads();
}
/ **** 首先調用category的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;
}
複製代碼
子類的+load以前會先調用父類的+load,先編譯,先調用 經過內存地址(IMP)直接調用
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_method_t load_method = (load_method_t)classes[i].method;
if (!cls) continue;
if (PrintLoading) {
_objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
}
// 直接經過IMP函數指針調用
// IMP(Class,SEL),load(cls,SEL)
(*load_method)(cls, SEL_load);
}
// Destroy the detached list.
if (classes) free(classes);
}
複製代碼
程序加載,去構建load列表
void load_images(const char *path __unused, const struct mach_header *mh)
{
// 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
{
rwlock_writer_t lock2(runtimeLock);
prepare_load_methods((const headerType *)mh);
}
// Call +load methods (without runtimeLock - re-entrant)
call_load_methods();
}
void prepare_load_methods(const headerType *mhdr)
{
size_t count, i;
runtimeLock.assertWriting();
// _getObjc2NonlazyClassList的順序與編譯順序相同
classref_t *classlist =
_getObjc2NonlazyClassList(mhdr, &count);
for (i = 0; i < count; i++) {
//定製load方法列表
schedule_class_load(remapClass(classlist[i]));
}
category_t **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
realizeClass(cls);
assert(cls->ISA()->isRealized());
add_category_to_loadable_list(cat);
}
}
複製代碼
構建load方法列表時,先添加父類load再添加子類load
static void schedule_class_load(Class cls)
{
if (!cls) return;
assert(cls->isRealized()); // _read_images should realize
if (cls->data()->flags & RW_LOADED) return;
//遞歸調用,先調用父類
schedule_class_load(cls->superclass);
//將類追加到列表末尾
add_class_to_loadable_list(cls);
cls->setInfo(RW_LOADED);
}
複製代碼
直接提取出IMP調用,並未通過消息轉發 但若是[Person load],只能調用到分類方法
向一個類第一次主動發送消息時調用。
當一個類的方法第一次被調用,會進入查找邏輯。並加入cache,第二次直接在cache讀取。
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. lookUpImpOrNil(cls, sel, nil, NO/*initialize*/, NO/*cache*/, YES/*resolver*/); #warning fixme build and search caches return _class_getMethod(cls, sel); } 複製代碼
/**
在一個類對象中查找某個SEL的IMP實現
*/
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
...
//若是須要初始化,而且未被初始化
if (initialize && !cls->isInitialized()) {
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
}
...
return imp;
}
複製代碼
優先初始化父類,而後初始化本身
void _class_initialize(Class cls)
{
...
...
//優先初始化父類
if (supercls && !supercls->isInitialized()) {
_class_initialize(supercls);
}
...
...
if (reallyInitialize) {
...
@try
#endif
{
callInitialize(cls);
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
}
#if __OBJC2__
@catch (...) {
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: +[%s initialize] "
"threw an exception",
pthread_self(), cls->nameForLogging());
}
@throw;
}
@finally
#endif
{
// Done initializing.
lockAndFinishInitializing(cls, supercls);
}
return;
}
else if (cls->isInitializing()) {
// We couldn't set INITIALIZING because INITIALIZING was already set. // If this thread set it earlier, continue normally. // If some other thread set it, block until initialize is done. // It's ok if INITIALIZING changes to INITIALIZED while we're here, // because we safely check for INITIALIZED inside the lock // before blocking. if (_thisThreadIsInitializingClass(cls)) { return; } else if (!MultithreadedForkChild) { waitForInitializeToComplete(cls); return; } else { // We're on the child side of fork(), facing a class that
// was initializing by some other thread when fork() was called.
_setThisThreadIsInitializingClass(cls);
performForkChildInitialize(cls, supercls);
}
}
else if (cls->isInitialized()) {
// Set CLS_INITIALIZING failed because someone else already
// initialized the class. Continue normally.
// NOTE this check must come AFTER the ISINITIALIZING case.
// Otherwise: Another thread is initializing this class. ISINITIALIZED
// is false. Skip this clause. Then the other thread finishes
// initialization and sets INITIALIZING=no and INITIALIZED=yes.
// Skip the ISINITIALIZING clause. Die horribly.
return;
}
else {
// We shouldn't be here. _objc_fatal("thread-safe class init in objc runtime is buggy!"); } } 複製代碼
對自身進行初始化
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
asm("");
}
複製代碼
Initialize
的調用屬於消息轉發,若是cls自己沒有實現,則會去父類查找並調用。
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
asm("");
}
複製代碼