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在一個程序中每一個類的一個程序中發送一個初始化一次,或是從它繼承的任何類中,都是在程序中發送第一條消息。(因此,當該類不使用時,該方法可能永遠不會被調用。)運行時發送一個線程安全的方式初始化消息。父類的調用一定在子類之前。
對比
相同點
- 在不考慮開發者主動使用的情況下,系統最多會調用一次
- 如果父類和子類都被調用,父類的調用一定在子類之前,
- 類中的方法優先于類別(Category)中的方法。
- 都是為了應用運行提前創建合適的運行環境
- 在使用時都不要過重地依賴于這兩個方法,除非真正必要
不同點
load是只要類所在文件被引用就會被調用(這里是引用進項目,不是被其他的文件引用),而initialize是在類或者其子類的第一個方法被調用前調用。所以如果類沒有被引用進項目,就不會有load調用;但即使類文件被引用進來,但是沒有使用,那么initialize也不會被調用。
總結 | +(void)load | +(void)initialize |
---|---|---|
執行時機 | 在程序運行后立即執行 | 在類的方法第一次被調時執行 |
若自身未定義,是否沿用父類的方法? | 否 | 是 |
類別中的定義 | 全都執行,但后于類中的方法 | 覆蓋類中的方法,只執行一個 |