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的區(qū)別在于:load是只要類所在文件被runtime引用就會被調(diào)用蝙搔,而initialize是在類或者其子類的第一個方法被調(diào)用前調(diào)用笨蚁。所以如果類沒有被引用進(jìn)項(xiàng)目,就不會有l(wèi)oad調(diào)用矮固;但即使類文件被引用進(jìn)來刑桑,但是沒有使用氯质,那么initialize也不會被調(diào)用。
它們的相同點(diǎn)在于:方法只會被runtime調(diào)用一次祠斧。
initialize和load的調(diào)用順序:SuperClass > SubClass, Class > Class Category闻察。Initialize 是通過msg_send
消息機(jī)制,所以當(dāng)調(diào)用子類的Initialize時會自動調(diào)用父類的琢锋。不需要通過[super initialize]
調(diào)用辕漂。然而load
是通過函數(shù)指針的形式調(diào)用。分類中的initialize
會覆蓋掉類中的吴超。分類中的load
則不會覆蓋掉子類中的钉嘹。
示例代碼在這里