+(void)initialize
理解:
當(dāng)有繼承關(guān)系的時(shí)候,會(huì)先調(diào)用父類的initialize,隨后再調(diào)用子類的initialize。
但是有的時(shí)候,若不需要調(diào)用父類的initialize,需要判斷如下,參見(jiàn)官方文檔。
Initializes the class before it receives its first message.
The runtime sends initialize to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program. Superclasses receive this message before their subclasses.
The runtime sends the initialize message to classes in a thread-safe manner. That is, initialize is run by the first thread to send a message to a class, and any other thread that tries to send a message to that class will block until initialize completes.
The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize]. If you want to protect yourself from being run multiple times, you can structure your implementation along these lines:
Listing 1
+(void)initialize {
if (self == [ClassName self]) {
// ... do the initialization ...
}
}
Because initialize is called in a blocking manner, it’s important to limit method implementations to the minimum amount of work necessary possible. Specifically, any code that takes locks that might be required by other classes in their initialize methods is liable to lead to deadlocks. Therefore, you should not rely on initialize for complex initialization, and should instead limit it to straightforward, class local initialization.
翻譯后:
在它接收第一個(gè)消息之前初始化這個(gè)類。
運(yùn)行時(shí)在類前面的程序中,或者任何繼承自它的類,在程序中發(fā)送它的第一個(gè)消息。超類在子類之前接收此消息。
運(yùn)行時(shí)以線程安全的方式將初始化消息發(fā)送到類。也就是說(shuō),初始化是由第一個(gè)線程運(yùn)行的,它向類發(fā)送一條消息,任何試圖向該類發(fā)送消息的線程都將阻塞,直到初始化完成為止。
如果子類沒(méi)有實(shí)現(xiàn)initialize,運(yùn)行時(shí)將調(diào)用繼承的實(shí)現(xiàn),或者如果子類顯式調(diào)用[super initialize],超類實(shí)現(xiàn)可以被多次調(diào)用。如果你想保護(hù)自己不被多次運(yùn)行,你可以沿著這些線來(lái)構(gòu)造你的實(shí)現(xiàn):
+(void)initialize{
if(self = =[ClassName self]){
/ /………
}
}
由于初始化被以阻塞的方式調(diào)用,所以將方法實(shí)現(xiàn)限制到盡可能少的工作是很重要的。具體地說(shuō),任何在初始化方法中使用其他類可能需要的鎖的代碼都可能導(dǎo)致死鎖。因此,您不應(yīng)該依賴于對(duì)復(fù)雜初始化的初始化,而是應(yīng)該將其限制為簡(jiǎn)單的類本地初始化。