標籤:
它們的特別之處,在於iOS會在運行期提前並且自動調用這兩個方法,而且很多對於類方法的規則(比如繼承,類別(Category))都有不同的處理。
先來看看NSObject Class Reference裡對這兩個方法說明:
+(void)initialize
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.
+(void)load
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.A category +load method is called after the class’s own +load method.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.
Apple的文檔很清楚地說明了initialize和load的區別在於:load是只要類所在檔案被引用就會被調用,而initialize是在類或者其子類的第一個方法被調用前調用。所以如果類沒有被引用進項目,就不會有load調用;但即使類檔案被引用進來,但是沒有使用,那麼initialize也不會被調用。它們的相同點在於:方法只會被調用一次。(其實這是相對runtime來說的,後邊會做進一步解釋)。文檔也明確闡述了方法調用的順序:父類(Superclass)的方法優先於子類(Subclass)的方法,類中的方法優先於類別(Category)中的方法。不過還有很多地方是文章中沒有解釋詳細的。所以再來看一些範例程式碼來明確其中應該注意的細節。
+(void)load與+(void)initialize初探
| |
|
|
| 執行時機 |
|
|
| 若自身未定義,是否沿用父類的方法? |
否 |
|
| 類別中的定義 |
全都執行,但後於類中的方法 |
覆蓋類中的方法,只執行一個 |
Objective C類方法load和initialize的區別