NSObject +(void)load 和+(void)initialize 方法的理解

runtime 源码,理解 +(void)load+(void)initialize 方法。html

零、官方文档

  • initialize Initializes the class before it receives its first message.git

  • load Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.github

根据文档,+load 方法只要文件被引用就会被调用,因此若是类没有被引进项目,就不会调用 +load+initialize 方法是在类或者子类的第一个方法(抛一个问题,那 runtime 调用 +load 方法呢,算第一个方法吗?)被调用以前调用,即便类被引用进项目,但没有被使用, +initialize 也不会被调用。二者都只会被调用一次。objective-c

1、实验田

Demo数组

# Father.h 和 Father.m
@interface Father : NSObject

@end

#import "Father.h"

#pragma mark - Father

@implementation Father

+ (void)load {
    # [self class];
    NSLog(@"%s", __FUNCTION__);
}

+ (void)initialize {
    NSLog(@"%s", __FUNCTION__);
}

@end
复制代码
# Son .h 和 .m
@interface Son : Father
@end

@implementation Son

+ (void)load {
    # [self class];
    NSLog(@"%s", __FUNCTION__);
}

+ (void)initialize {
    NSLog(@"%s", __FUNCTION__);
}

@end
复制代码
# Category Active of Son .h and .m
@interface Son (Active)
@end

@implementation Son (Active)

+ (void)load {
    # [self class];
    NSLog(@"%s", __FUNCTION__);
}

+ (void)initialize {
    NSLog(@"%s", __FUNCTION__);
}

@end
复制代码
# Category Stiff of Son .h and .m
@interface Son (Stiff)
@end

@implementation Son (Stiff)

+ (void)load {
    # [self class];
    NSLog(@"%s", __FUNCTION__);
}

+ (void)initialize {
    NSLog(@"%s", __FUNCTION__);
}

@end
复制代码

结果以下安全

# 父类的方法优先于子类的方法,类中的方法优先于类别中的方法。
2018-02-01 10:59:11.957088+0800 LoadAndInitializePlot[21886:9588221] +[Father load]
2018-02-01 10:59:11.957867+0800 LoadAndInitializePlot[21886:9588221] +[Son load]
2018-02-01 10:59:11.957997+0800 LoadAndInitializePlot[21886:9588221] +[Son(Active) load]
2018-02-01 10:59:11.958132+0800 LoadAndInitializePlot[21886:9588221] +[Son(Stiff) load]
复制代码

在 Father load 中添加 [self class];,结果以下bash

# 调用了 Father 中的方法,第一个方法`[self class];`被调用时,在调用方法以前执行 `+initialize` 方法。能够看出,虽然引用了 Son 类,但没有调用 Son 的 `+initalize`,同时 runtime 对 `+(void)load` 的调用不视为调用类的第一个方法,若是是子类 Son 也会调用 `+initialize` 的。
2018-02-01 11:03:38.424049+0800 LoadAndInitializePlot[21961:9595895] +[Father initialize]
2018-02-01 11:03:38.424803+0800 LoadAndInitializePlot[21961:9595895] +[Father load]
2018-02-01 11:03:38.424953+0800 LoadAndInitializePlot[21961:9595895] +[Son load]
2018-02-01 11:03:38.425123+0800 LoadAndInitializePlot[21961:9595895] +[Son(Active) load]
2018-02-01 11:03:38.425418+0800 LoadAndInitializePlot[21961:9595895] +[Son(Stiff) load]
复制代码

在 Son load 中添加 [self class];,结果以下两种(在Build Phases -> Compile Sources 中拖动类别的上下顺序,也就是编译的前后顺序)。根据 runtime 对 category 加载过程,一个类的全部类别的方法被取出放在 method_list_t 中,另外,这里的新生成的 category 的方法会先于 早期生成的 category 的方法,倒序添加的。生成全部 method 的 list 以后,将全部的方法 前序 添加到类的方法数组中。原来的类的方法被 category 的方法覆盖,但被覆盖的方法依旧还在里面。这是由于系统调用方法,根据方法名在 method_list 中查找方法,找到第一个名字匹配的方法以后就不继续往下找了。每次调用都是 method_list 中最前面的同名方法,其余的方法仍在 method_list 中。app

# Son (Stiff) 类别在 Son (Active) 后编译
2018-02-01 11:46:45.558933+0800 LoadAndInitializePlot[22604:9665625] +[Father load]
2018-02-01 11:46:45.559605+0800 LoadAndInitializePlot[22604:9665625] +[Father initialize]
2018-02-01 11:46:45.559735+0800 LoadAndInitializePlot[22604:9665625] +[Son(Stiff) initialize]
2018-02-01 11:46:45.559876+0800 LoadAndInitializePlot[22604:9665625] +[Son load]
2018-02-01 11:46:45.560021+0800 LoadAndInitializePlot[22604:9665625] +[Son(Active) load]
2018-02-01 11:46:45.560125+0800 LoadAndInitializePlot[22604:9665625] +[Son(Stiff) load]
复制代码
# Son (Active) 类别在 Son (Stiff) 后编译
2018-02-01 11:50:33.255480+0800 LoadAndInitializePlot[22659:9671829] +[Father load]
2018-02-01 11:50:33.256105+0800 LoadAndInitializePlot[22659:9671829] +[Father initialize]
2018-02-01 11:50:33.256236+0800 LoadAndInitializePlot[22659:9671829] +[Son(Active) initialize]
2018-02-01 11:50:33.256363+0800 LoadAndInitializePlot[22659:9671829] +[Son load]
2018-02-01 11:50:33.256449+0800 LoadAndInitializePlot[22659:9671829] +[Son(Stiff) load]
2018-02-01 11:50:33.256531+0800 LoadAndInitializePlot[22659:9671829] +[Son(Active) load]
复制代码

在 Son load 中添加 [self class];,移除 Son 主类和两个类别中的 +initilize 方法。less

# `+(void)initialize` 自身未定义,会沿用父类的方法。
2018-02-01 11:54:27.282176+0800 LoadAndInitializePlot[22722:9678734] +[Father load]
2018-02-01 11:54:27.282749+0800 LoadAndInitializePlot[22722:9678734] +[Father initialize]
2018-02-01 11:54:27.282843+0800 LoadAndInitializePlot[22722:9678734] +[Father initialize]
2018-02-01 11:54:27.282955+0800 LoadAndInitializePlot[22722:9678734] +[Son load]
2018-02-01 11:54:27.283046+0800 LoadAndInitializePlot[22722:9678734] +[Son(Stiff) load]
2018-02-01 11:54:27.283157+0800 LoadAndInitializePlot[22722:9678734] +[Son(Active) load]
复制代码

在 Son load 中添加 [self class];,移除 两个类别的 +initilize 方法。ide

# 根据以上的 runtime 中的分析可知,`+(void)initialize`会“覆盖”类中的方法,只执行一个。
2018-02-01 11:56:00.047404+0800 LoadAndInitializePlot[22756:9681679] +[Father load]
2018-02-01 11:56:00.051067+0800 LoadAndInitializePlot[22756:9681679] +[Father initialize]
2018-02-01 11:56:00.051389+0800 LoadAndInitializePlot[22756:9681679] +[Son initialize]
2018-02-01 11:56:00.051745+0800 LoadAndInitializePlot[22756:9681679] +[Son load]
2018-02-01 11:56:00.052070+0800 LoadAndInitializePlot[22756:9681679] +[Son(Stiff) load]
2018-02-01 11:56:00.052350+0800 LoadAndInitializePlot[22756:9681679] +[Son(Active) load]
复制代码

1、+(void)load 的理解

+load 方法是 Objective-C 中 NSObject 的一个方法,在整个文件刚被加载到运行时,在 main 函数调用以前被 ObjC runtime 调用的钩子方法

常见理论知识汇总

  • 调用顺序:父类 > 子类 > 分类
  • 调用时机:Objective-C 运行时初始化时,每当有新的镜像library map 到运行时调用。
  • 调用次数:一次
  • 线程安全:load 方法是线程安全的,内部使用了锁,应避免线程阻塞在 load 中。
  • 常见场景:load 中实现 Method Swizzle。
  • one more thing:若是一个类自己没有 load 方法,无论其父类是否实现 load,都不会调用,主类和分类都执行。

基于 runtime 源码分析

针对 runtime 源码 objc4-723 ,作一下探讨。 xnu 内核为程序准备好以后,将控制权交个 dyld 负责后续工做,dyld 是 Apple 的动态连接器, the dynamic link editor 的缩写。此过程内核态切换到用户态,dyld 在用户态。

####_objc_init 每当 libSystem 在 library 初始化以前都会调用 _objc_init方法,dyld 在方法中注册 load_images 回调。

/***********************************************************************
* _objc_init
* Bootstrap initialization. Registers our image notifier with dyld.
* Called by libSystem BEFORE library initialization time
**********************************************************************/
# pragma mark - ObjC runtime 初始化 注册 load_images 回调
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();
    lock_init();
    exception_init();

    _dyld_objc_notify_register(&map_2_images, load_images, unmap_image);
}
复制代码

load_images

因此每当有新的 library 被 map 到 runtime 时,调用 load_images 方法。

/***********************************************************************
* load_images
* Process +load in the given images which are being mapped in by dyld.
*
* Locking: write-locks runtimeLock and loadMethodLock
**********************************************************************/
extern bool hasLoadMethods(const headerType *mhdr);
extern void prepare_load_methods(const headerType *mhdr);

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();
}
复制代码

prepare_load_methods

在主类的父类和自身添加到全局静态结构体 loadable_list 中以后,添加主类的分类,将分类添加到全局静态结构体 loadable_categories 中。因此子类优先分类。

void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertWriting();

    classref_t *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    for (i = 0; i < count; i++) {
        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);
    }
}
复制代码

schedule_class_load

递归调用 schedule_class_load ,在将当前类加入全局静态结构体 loadable_classes 以前,将父类加入其中,待后续加载。保证了父类在子类以前调用 load 方法。

/***********************************************************************
* 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
    schedule_class_load(cls->superclass);

    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}
复制代码

call_load_methods

当 library 加载到运行时,prepare 调用结束,执行 call_load_methods();

/***********************************************************************
* 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) { call_class_loads(); } // 2. Call category +loads ONCE 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; } 复制代码

附录:

add_class_to_loadable_listadd_category_to_loadable_list方法

// List of classes that need +load called (pending superclass +load)
// This list always has superclasses first because of the way it is constructed
static struct loadable_class *loadable_classes = nil;
static int loadable_classes_used = 0;
static int loadable_classes_allocated = 0;

// List of categories that need +load called (pending parent class +load)
static struct loadable_category *loadable_categories = nil;
static int loadable_categories_used = 0;
static int loadable_categories_allocated = 0;


/***********************************************************************
* add_class_to_loadable_list
* Class cls has just become connected. Schedule it for +load if
* it implements a +load method.
**********************************************************************/
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 * 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.
**********************************************************************/
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++; } 复制代码

call_class_loadscall_category_loads 方法

/***********************************************************************
* 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_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);
}


/***********************************************************************
* 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_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)); } (*load_method)(cls, SEL_load); cats[i].cat = nil; } } // Compact detached list (order-preserving) shift = 0; for (i = 0; i < used; i++) { if (cats[i].cat) { cats[i-shift] = cats[i]; } else { shift++; } } used -= shift; // Copy any new +load candidates from the new list to the detached list. new_categories_added = (loadable_categories_used > 0); for (i = 0; i < loadable_categories_used; i++) { if (used == allocated) { allocated = allocated*2 + 16; cats = (struct loadable_category *) realloc(cats, allocated * sizeof(struct loadable_category)); } cats[used++] = loadable_categories[i]; } // Destroy the new list. if (loadable_categories) free(loadable_categories); // Reattach the (now augmented) detached list. // But if there's nothing left to load, destroy the list.
    if (used) {
        loadable_categories = cats;
        loadable_categories_used = used;
        loadable_categories_allocated = allocated;
    } else {
        if (cats) free(cats);
        loadable_categories = nil;
        loadable_categories_used = 0;
        loadable_categories_allocated = 0;
    }

    if (PrintLoading) {
        if (loadable_categories_used != 0) {
            _objc_inform("LOAD: %d categories still waiting for +load\n",
                         loadable_categories_used);
        }
    }

    return new_categories_added;
}

复制代码

+(void)initialize 的理解

+(void)initialize 是在类或者它的子类收到第一条消息(实例方法、类方法)以前被调用的。

常见理论知识汇总

  • 调用顺序:父类 > 子类(或分类)
  • 调用时机:Objective-C 运行时初始化时,每当有新的镜像library map 到运行时调用。
  • 调用次数:屡次,若是子类未实现+(void)initialize ,父类+(void)initialize 会被调用屡次
  • 线程安全:在initialize方法收到调用时,运行环境基本健全。initialize的运行过程当中是能保证线程安全的。
  • 常见场景:稍微普遍,初始化工做,或者单例模式的实现方案。

基于 runtime 源码分析

lookUpImpOrForward

当一个类收到消息时,runtime 会经过 IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver) 方法查找方法的实现返回函数指针 IMP,或者进行消息转发。

/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup. 
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known. 
*   If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use 
*   must be converted to _objc_msgForward or _objc_msgForward_stret.
*   If you don't want forwarding at all, use lookUpImpOrNil() instead. **********************************************************************/ IMP lookUpImpOrForward(Class cls, SEL sel, id inst, bool initialize, bool cache, bool resolver) { ... if (initialize && !cls->isInitialized()) { _class_initialize (_class_getNonMetaClass(cls, inst)); // If sel == initialize, _class_initialize will send +initialize and // then the messenger will send +initialize again after this // procedure finishes. Of course, if this is not being called // from the messenger then it won't happen. 2778172
    }

    ...
}
复制代码

_class_initialize

若是类没有被初始化,会调用 _class_initialize 进行初始化,对入参的参数父类递归的调用 _class_initialize,这也就是父类优先子类调用的本质。是否是对「Talk is cheap. Show me the code.」深表体会;)

/***********************************************************************
* class_initialize.  Send the '+initialize' message on demand to any
* uninitialized class. Force initialization of superclasses first.
**********************************************************************/
void _class_initialize(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->superclass;
    if (supercls  &&  !supercls->isInitialized()) {
        _class_initialize(supercls);
    }
    
    // Try to atomically set CLS_INITIALIZING.
    {
        monitor_locker_t lock(classInitLock);
        if (!cls->isInitialized() && !cls->isInitializing()) {
            cls->setInitializing();
            reallyInitialize = YES;
        }
    }
    
    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); // 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: calling +[%s initialize]",
                         cls->nameForLogging());
        }

        // Exceptions: A +initialize call that throws an exception 
        // is deemed to be a complete and successful +initialize.
        @try {
            callInitialize(cls);

            if (PrintInitializing) {
                _objc_inform("INITIALIZE: finished +[%s initialize]",
                             cls->nameForLogging());
            }
        }
        @catch (...) {
            if (PrintInitializing) {
                _objc_inform("INITIALIZE: +[%s initialize] threw an exception",
                             cls->nameForLogging());
            }
            @throw;
        }
        @finally {
            // Done initializing. 
            // If the superclass is also done initializing, then update 
            //   the info bits and notify waiting threads.
            // If not, update them later. (This can happen if this +initialize 
            //   was itself triggered from inside a superclass +initialize.)
            monitor_locker_t lock(classInitLock);
            if (!supercls  ||  supercls->isInitialized()) {
                _finishInitializing(cls, supercls);
            } else {
                _finishInitializingAfter(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 { waitForInitializeToComplete(cls); return; } } 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!");
    }
}
复制代码

callInitialize 中使用 objc_msgSend 方式对 +(void)initialize 进行调用,也就是和普通方法走消息发送的流程,若是子类没有实现,走父类的方法,若是分类实现,就会对主类进行“覆盖”,若是多个分类,不肯定调用哪个分类的同名方法,须要看编译的过程。

void callInitialize(Class cls)
{
    ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
    asm("");
}
复制代码

Tips

若是子类没有实现 +(void)initialize,父类会被调用屡次,只想调用父类 initialize 一次呢。

+ (void)initialize {
  if (self == [ClassName self]) {
    
  }
}
# 或者 dispatch_once 了
复制代码

推荐文章

相关文章
相关标签/搜索