1. 程式人生 > >IOS雜筆- 7(類方法load與initialize的區別 淺析)

IOS雜筆- 7(類方法load與initialize的區別 淺析)

ram rom 運行 所在 ttr app 函數 tor static

在介紹兩種類方法之前,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:

  1. All initializers in any framework you link to.
  2. All +load methods in your image.
  3. All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.
  4. All initializers in frameworks that link to you.

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.

翻譯:加載消息被發送到動態加載和靜態鏈接的類和類別,但只有當新加載的類或類實現了可以響應的方法。初始化的順序如下:

在任何框架鏈接到你所有的初始化。

所有的負載方法在您的圖像。

所有c++靜態初始化器和C / c++使用__attribute__(構造函數)函數在你的形象

所有初始化框架鏈接到你。

在一個自定義實現負載可以因此安全消息其他不相關的類相同的圖像,但任何負載方法的實現類可能尚未運行。

------------------------------------------------

Apple的文檔很清楚地說明了initialize和load的區別在於:load是只要類所在文件被引用就會被調用,而initialize是在類或者其子類的第一個方法被調用前調用。所以如果類沒有被引用進項目,就不會有load調用;但即使類文件被引用進來,但是沒有使用,那麽initialize也不會被調用。

它們的相同點在於:方法只會被調用一次。(其實這是相對runtime來說的,後邊會做進一步解釋)。

文檔也明確闡述了方法調用的順序:父類(Superclass)的方法優先於子類(Subclass)的方法,類中的方法優先於類別(Category)中的方法。

IOS雜筆- 7(類方法load與initialize的區別 淺析)