iphoneobjective-cxcodeinterfaceconstructor

+(void) initialize in objective-c class static variables constructor


I found some sample code from here.

static UIImage *backgroundImageDepressed;

/**
 *
 */
@implementation DecimalPointButton

+ (void) initialize {
    backgroundImageDepressed = [[UIImage imageNamed:@"decimalKeyDownBackground.png"] retain];
}

Is it something like this - +(void) initialize method initialize static variables of a class ( interface ) in Objective C? I have never seen this before.


Solution

  • This +initialize method is described in The Objective-C Runtime.

    The runtime system sends an initialize message to every class object before the class receives any other messages and after its superclass has received the initialize message. This gives the class a chance to set up its runtime environment before it’s used. If no initialization is required, you don’t need to write an initialize method to respond to the message.

    For example, when [DecimalPointButton alloc] is called, the runtime will check if [DecimalPointButton initialize] has been called. If not, it will +initialize the class. This ensure the backgroundImageDepressed image is ready before any instances of DecimalPointButton are constructed.