13類方法load和initialize的區(qū)別

http://www.cnblogs.com/ider/archive/2012/09/29/objective_c_load_vs_initialize.html

在objc語言里,有2個類初始化方法,+(void)load和+(void)initialize。
  • . +(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的區(qū)別在于:load是只要類所在文件被引用就會被調用,而initialize是在類或者其子類的第一個方法被調用前調用。所以如果類沒有被引用進項目,就不會有l(wèi)oad調用;但即使類文件被引用進來,但是沒有使用,那么initialize也不會被調用。

它們的相同點在于:方法只會被調用一次。(其實這是相對runtime來說的,后邊會做進一步解釋)。
文檔也明確闡述了方法調用的順序:父類(Superclass)的方法優(yōu)先于子類(Subclass)的方法,類中的方法優(yōu)先于類別(Category)中的方法。
不過還有很多地方是文章中沒有解釋詳細的。所以再來看一些示例代碼來明確其中應該注意的細節(jié)。

    1. load,是加載類的時候,這里是Constants類,就會調用。也就是說,ios應用啟動的時候,就會加載所有的類,就會調用這個方法。

      這樣有個缺點,當加載類需要很昂貴的資源,或者比較耗時的時候,可能造成不良的用戶體驗,或者系統(tǒng)的抖動(dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{});用GCD可能會好點)。

    1. 這時候,就要考慮initialize方法了。這個方法可看作類加載的延時加載方法。類加載后并不執(zhí)行該方法。只有當實例化該類的實例的時候,才會在第一個實例加載前執(zhí)行該方法。比如:
      [Constants alloc];
      alloc將為Constants實例在堆上分配變量。這時調用一次initialize方法,而且僅調用一次,也就是說再次alloc操作的時候,不會再調用initialize方法了。
      initialize 會在運行時僅被觸發(fā)一次,如果沒有向類發(fā)送消息的話,這個方法將不會被調用。這個方法的調用是線程安全的。父類會比子類先收到此消息。

如果希望在類及其Categorgy中執(zhí)行不同的初始化的話可以使用+load
+(void)load; 在Objective-C運行時載入類或者Category時被調用
這個方法對動態(tài)庫和靜態(tài)庫中的類或(Category)都有效.

總結:

方法對比.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容