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. The runtime sends theinitialize
message to classes in a thread-safe manner. Superclasses receive this message before their subclasses. 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:
-
+(void)initialize{
-
if(self== [ClassNameself]){
-
// ... do the initialization ...
-
}
-
}
Because initialize
is called in a thread-safe manner and the order of initialize
being called on different classes is not guaranteed, it’s important to do the minimum amount of work necessary in initialize
methods. 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.