美文网首页iOS 开发iOS DeveloperiOS 开发
iOS的load方法与initialize方法

iOS的load方法与initialize方法

作者: TerryZhang | 来源:发表于2016-06-21 19:51 被阅读325次

    iOS的load方法与initialize方法

    load

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

    当类(Class)或者类别(Category)加入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.
    调用所有的Framework中的初始化方法

    All +load methods in your image.
    调用所有的+load方法

    All C++ static initializers and C/C++ attribute(constructor) functions in your image.
    调用C++的静态初始化方及C/C++中的attribute(constructor)函数

    All initializers in frameworks that link to you.
    调用所有链接到目标文件的framework中的初始化方法

    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.
    一个Category的+load方法在被其扩展的类的自有+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.
    在+load方法中,可以安全地向同一二进制包中的其它无关的类发送消息,但接收消息的类中的+load方法可能尚未被调用。

    initialize

    Initializes the class before it receives its first message.

    在这个类接收第一条消息之前调用。

    Discussion

    The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

    Runtime在一个程序中每一个类的一个程序中发送一个初始化一次,或是从它继承的任何类中,都是在程序中发送第一条消息。(因此,当该类不使用时,该方法可能永远不会被调用。)运行时发送一个线程安全的方式初始化消息。父类的调用一定在子类之前。

    对比

    相同点

    1. 在不考虑开发者主动使用的情况下,系统最多会调用一次
    2. 如果父类和子类都被调用,父类的调用一定在子类之前,
    3. 类中的方法优先于类别(Category)中的方法。
    4. 都是为了应用运行提前创建合适的运行环境
    5. 在使用时都不要过重地依赖于这两个方法,除非真正必要

    不同点

    load是只要类所在文件被引用就会被调用(这里是引用进项目,不是被其他的文件引用),而initialize是在类或者其子类的第一个方法被调用前调用。所以如果类没有被引用进项目,就不会有load调用;但即使类文件被引用进来,但是没有使用,那么initialize也不会被调用。

    总结 +(void)load +(void)initialize
    执行时机 在程序运行后立即执行 在类的方法第一次被调时执行
    若自身未定义,是否沿用父类的方法?
    类别中的定义 全都执行,但后于类中的方法 覆盖类中的方法,只执行一个

    相关文章

      网友评论

        本文标题:iOS的load方法与initialize方法

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