Apple的文檔很清楚地說明了initialize和load的區(qū)別在于:load是只要類所在文件被引用就會被調用航棱,而initialize是在類或者其子類的第一個方法被調用前調用婴削。所以如果類沒有被引用進項目,就不會有l(wèi)oad調用负敏;但即使類文件被引用進來,但是沒有使用骂束,那么initialize也不會被調用苛谷。
它們的相同點在于:方法只會被調用一次。(其實這是相對runtime來說的格郁,后邊會做進一步解釋)腹殿。
文檔也明確闡述了方法調用的順序:父類(Superclass)的方法優(yōu)先于子類(Subclass)的方法独悴,類中的方法優(yōu)先于類別(Category)中的方法。
下面是官方給出的說明
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.
Theloadmessage 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+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.