load和Initialize的特別之處:
1恕稠,IOS會在運(yùn)行期提前并且自動調(diào)用這兩個方法琅绅。
2,在繼承和類別這兩種場景中鹅巍,系統(tǒng)對這兩個方法的處理是不同的奉件。
load和initialize的一般應(yīng)用場景:
因?yàn)檫@兩個方法是在程序運(yùn)行一開始就被調(diào)用的方法,所以我們可以利用他們在類被使用前昆著,做一些預(yù)處理工作县貌。比如讓類自動將自身類名保存到一個NSDictionary中。
NSObject Class Reference里對這兩個方法說明:
+(void)initialize
The runtime sendsinitializeto 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
Theloadmessage is sent to classes and categories that are both dynamically loaded and statically linked, butonly 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+loadmethods 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+loadmethod is called after all of its superclasses’+loadmethods.
A category+loadmethod is called after the class’s own+loadmethod.
In a custom implementation ofloadyou can therefore safely message other unrelated classes from the same image, but anyloadmethods implemented by those classes may not have run yet.
從文檔可以看出:
load和initialize的區(qū)別在于:load是只要類所在文件被引用凑懂,就會被調(diào)用煤痕,而initialize是在類或者其子類的第一個方法被調(diào)用前調(diào)用。
load和Initialize的相同點(diǎn)在于:方法只會被調(diào)用一次接谨。(其實(shí)這是相對runtime來說的摆碉,后邊就做進(jìn)一步解釋)。
資料鏈接:
[IDER]:
http://blog.iderzheng.com
http://blog.iderzheng.com/objective-c-load-vs-initialize/
[MrPeak雜貨鋪]:http://blog.csdn.net/hanangellove/article/details/45033453
[知乎上的一個怎么面試iOS工程師的問題]:
http://blog.csdn.net/hanangellove/article/details/45033453