apple对这两个方法的描述:
- (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:
1 All initializers in any framework you link to.
2 All +load methods in your image.
3 All C static initializers and C/C attribute(constructor) functions in your image.
4 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.
initialize和load的区别在于:load是只要类所在文件被runtime引用就会被调用,而initialize是在类或者其子类的第一个方法被调用前调用。所以如果类没有被引用进项目,就不会有load调用;但即使类文件被引用进来,但是没有使用,那么initialize也不会被调用。
它们的相同点在于:方法只会被runtime调用一次。
initialize和load的调用顺序:SuperClass > SubClass, Class > Class Category。Initialize 是通过msg_send
消息机制,所以当调用子类的Initialize时会自动调用父类的。不需要通过[super initialize]
调用。然而load
是通过函数指针的形式调用。分类中的initialize
会覆盖掉类中的。分类中的load
则不会覆盖掉子类中的。
示例代码在这里
网友评论