IOS雜筆- 7(類方法load與initialize的區別 淺析),iosinitialize
在介紹兩種類方法之前,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:
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)中的方法。