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是只要類所在文件被引用就會被調(diào)用,而initialize是在類或者其子類的第一個方法被調(diào)用前調(diào)用。所以如果類沒有被引用進項目,就不會有l(wèi)oad調(diào)用;但即使類文件被引用進來,但是沒有使用,那么initialize也不會被調(diào)用。
它們的相同點在于:方法只會被調(diào)用一次。(其實這是相對runtime來說的,后邊會做進一步解釋)。
文檔也明確闡述了方法調(diào)用的順序:父類(Superclass)的方法優(yōu)先于子類(Subclass)的方法,類中的方法優(yōu)先于類別(Category)中的方法。
不過還有很多地方是文章中沒有解釋詳細的。所以再來看一些示例代碼來明確其中應(yīng)該注意的細節(jié)。
-
load,是加載類的時候,這里是Constants類,就會調(diào)用。也就是說,ios應(yīng)用啟動的時候,就會加載所有的類,就會調(diào)用這個方法。
這樣有個缺點,當加載類需要很昂貴的資源,或者比較耗時的時候,可能造成不良的用戶體驗,或者系統(tǒng)的抖動(dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{});用GCD可能會好點)。
-
- 這時候,就要考慮initialize方法了。這個方法可看作類加載的延時加載方法。類加載后并不執(zhí)行該方法。只有當實例化該類的實例的時候,才會在第一個實例加載前執(zhí)行該方法。比如:
[Constants alloc];
alloc將為Constants實例在堆上分配變量。這時調(diào)用一次initialize方法,而且僅調(diào)用一次,也就是說再次alloc操作的時候,不會再調(diào)用initialize方法了。
initialize 會在運行時僅被觸發(fā)一次,如果沒有向類發(fā)送消息的話,這個方法將不會被調(diào)用。這個方法的調(diào)用是線程安全的。父類會比子類先收到此消息。
- 這時候,就要考慮initialize方法了。這個方法可看作類加載的延時加載方法。類加載后并不執(zhí)行該方法。只有當實例化該類的實例的時候,才會在第一個實例加載前執(zhí)行該方法。比如:
如果希望在類及其Categorgy中執(zhí)行不同的初始化的話可以使用+load
+(void)load; 在Objective-C運行時載入類或者Category時被調(diào)用
這個方法對動態(tài)庫和靜態(tài)庫中的類或(Category)都有效.
總結(jié):