Two things to note here.
First, as you say the code is "using if (self == [Car class])
to check whether the self is referring to class itself or not". The method class
returns the class object for Car
, and self
will be the same object if initialize
is being called on Car
.
Second, how could the class method initialize
of Car
be called on anything other than Car
itself - it belongs to the class after all?
The answer to this lies in inheritance. The +initialize
of Car
will be called once before any instance of Car
is created. However it will be also called once for every subclass of Car
before the first instance of that subclass is created. E.g. if you have a class:
@interface Volvo : Car
...
@end
Then if Volvo
has an +initialize
then it will be called before the first instance of Volvo
is created and Car
's +initialize
will also be called before the first instance of Volvo
is created. This is why you will often see class initializers with an if
statement to check for self
being the class itself - it ensures the code is only executed once and not once per subclass as well.
HTH