iOS的load方法與initialize方法
load
Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.
當(dāng)類(Class)或者類別(Category)加入Runtime中時(shí)(就是被引用的時(shí)候)。
實(shí)現(xiàn)該方法,可以在加載時(shí)做一些類特有的操作。
Discussion
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:
All initializers in any framework you link to.
調(diào)用所有的Framework中的初始化方法
All +load methods in your image.
調(diào)用所有的+load方法
All C++ static initializers and C/C++ attribute(constructor) functions in your image.
調(diào)用C++的靜態(tài)初始化方及C/C++中的attribute(constructor)函數(shù)
All initializers in frameworks that link to you.
調(diào)用所有鏈接到目標(biāo)文件的framework中的初始化方法
In addition:
A class’s +load method is called after all of its superclasses’ +load methods.
一個(gè)類的+load方法在其父類的+load方法后調(diào)用
A category +load method is called after the class’s own +load method.
一個(gè)Category的+load方法在被其擴(kuò)展的類的自有+load方法后調(diào)用
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.
在+load方法中,可以安全地向同一二進(jìn)制包中的其它無關(guān)的類發(fā)送消息,但接收消息的類中的+load方法可能尚未被調(diào)用。
initialize
Initializes the class before it receives its first message.
在這個(gè)類接收第一條消息之前調(diào)用。
Discussion
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.
Runtime在一個(gè)程序中每一個(gè)類的一個(gè)程序中發(fā)送一個(gè)初始化一次,或是從它繼承的任何類中,都是在程序中發(fā)送第一條消息。(因此,當(dāng)該類不使用時(shí),該方法可能永遠(yuǎn)不會被調(diào)用。)運(yùn)行時(shí)發(fā)送一個(gè)線程安全的方式初始化消息。父類的調(diào)用一定在子類之前。
對比
相同點(diǎn)
- 在不考慮開發(fā)者主動(dòng)使用的情況下,系統(tǒng)最多會調(diào)用一次
- 如果父類和子類都被調(diào)用,父類的調(diào)用一定在子類之前,
- 類中的方法優(yōu)先于類別(Category)中的方法。
- 都是為了應(yīng)用運(yùn)行提前創(chuàng)建合適的運(yùn)行環(huán)境
- 在使用時(shí)都不要過重地依賴于這兩個(gè)方法,除非真正必要
不同點(diǎn)
load是只要類所在文件被引用就會被調(diào)用(這里是引用進(jìn)項(xiàng)目,不是被其他的文件引用),而initialize是在類或者其子類的第一個(gè)方法被調(diào)用前調(diào)用。所以如果類沒有被引用進(jìn)項(xiàng)目,就不會有l(wèi)oad調(diào)用;但即使類文件被引用進(jìn)來,但是沒有使用,那么initialize也不會被調(diào)用。
總結(jié) | +(void)load | +(void)initialize |
---|---|---|
執(zhí)行時(shí)機(jī) | 在程序運(yùn)行后立即執(zhí)行 | 在類的方法第一次被調(diào)時(shí)執(zhí)行 |
若自身未定義,是否沿用父類的方法? | 否 | 是 |
類別中的定義 | 全都執(zhí)行,但后于類中的方法 | 覆蓋類中的方法,只執(zhí)行一個(gè) |