+(void)initialize
理解:
当有继承关系的时候,会先调用父类的initialize,随后再调用子类的initialize。
但是有的时候,若不需要调用父类的initialize,需要判断如下,参见官方文档。
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.
翻译后:
在它接收第一个消息之前初始化这个类。
运行时在类前面的程序中,或者任何继承自它的类,在程序中发送它的第一个消息。超类在子类之前接收此消息。
运行时以线程安全的方式将初始化消息发送到类。也就是说,初始化是由第一个线程运行的,它向类发送一条消息,任何试图向该类发送消息的线程都将阻塞,直到初始化完成为止。
如果子类没有实现initialize,运行时将调用继承的实现,或者如果子类显式调用[super initialize],超类实现可以被多次调用。如果你想保护自己不被多次运行,你可以沿着这些线来构造你的实现:
+(void)initialize{
if(self = =[ClassName self]){
/ /………
}
}
由于初始化被以阻塞的方式调用,所以将方法实现限制到尽可能少的工作是很重要的。具体地说,任何在初始化方法中使用其他类可能需要的锁的代码都可能导致死锁。因此,您不应该依赖于对复杂初始化的初始化,而是应该将其限制为简单的类本地初始化。
网友评论