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 // 1.调用类的 load 方法 while (loadable_classes_used > 0) { call_class_loads(); } // 2. Call category +loads ONCE // 2.调用分类的 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方法。
查看load方法的调用源码,在 objc-loadmethod.m 文件中
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()); } (*load_method)(cls, SEL_load); } // Destroy the detached list. if (classes) free(classes);}
void callInitialize(Class cls){ ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize); asm("");}