load和Initialize的特别之处:
1,IOS会在运行期提前并且自动调用这两个方法。
2,在继承和类别这两种场景中,系统对这两个方法的处理是不同的。
load和initialize的一般应用场景:
因为这两个方法是在程序运行一开始就被调用的方法,所以我们可以利用他们在类被使用前,做一些预处理工作。比如让类自动将自身类名保存到一个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的区别在于:load是只要类所在文件被引用,就会被调用,而initialize是在类或者其子类的第一个方法被调用前调用。
load和Initialize的相同点在于:方法只会被调用一次。(其实这是相对runtime来说的,后边就做进一步解释)。
资料链接:
[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