美文网首页
iOS +load方法

iOS +load方法

作者: SnoopPanda | 来源:发表于2020-05-11 11:18 被阅读0次
    官方文档
    Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.
    重点:在类和分类加入Runtime的时候调用
    
    Discussion
    
    The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.
    
    The order of initialization is as follows:
    
    All initializers in any framework you link to.
    
    All +load methods in your image.
    
    All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.
    
    All initializers in frameworks that link to you.
    
    In addition:
    
    A class’s +load method is called after all of its superclasses’ +load methods.
    父类的+load方法调用时间优先与子类的+load方法
    A category +load method is called after the class’s own +load method.
    分类的+load方法在主类之后调用
    
    In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.
    
    Demo验证
    image.png
    结果

    1.在main方法执行之前,进行类的加载
    2.Compile Source列表里面的顺序决定了,没有继承关系的两个类的加载顺序
    3.主类的加载优先于分类
    4.父类的加载优先于子类
    5.load方法只执行一次
    tips:子类调用[super load],并不会多次调用父类的load

    应用场景

    因为load方法只在加入runtime的时候执行一次,可以在load方法里面使用Method Swizzling进行方法替换

    相关文章

      网友评论

          本文标题:iOS +load方法

          本文链接:https://www.haomeiwen.com/subject/aavynhtx.html