Q:

What is the functionality of method called class in objective-C

Hi I was studying about initialize class method in objective-C. I came across this code which confused me 
+ (void)initialize {
    if (self == [Car class]) // what is the use of method class??
    {
        // Makes sure this isn't executed more than once
        _defaultModel = @"Nissan Versa"; // initializing the static variable  _defaultModel
    }
}

Here I know that we're using if (self == [Car class]) to check whether  the self is referring to class itself or not. But what is the functionality of method class in [Car class] . I'm a newbie and I'm learning objective-C from couple of weeks when I searched for answers for this question all i got is difference b/w class methods and instance methods which I know. So please tell me what is the functionality of method class. Thanks in advance .

A:

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

