Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+(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.

like image 346
Sagar Kothari Avatar asked Jun 15 '10 06:06

Sagar Kothari


People also ask

Can static variables be initialized in constructor?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Are static variables initialized before constructor?

All static members are always initialized before any class constructor is being called.

Can a static variable be initialized in a constructor C++?

As static variables are initialized only once and are shared by all objects of a class, the static variables are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).

Do static variables get initialized C?

The static variable is only initialized the first time when a function is called. In a static variable, the memory of a static variable is allocated. A global static variable is not accessible outside the program.


1 Answers

This +initialize method is described in The Objective-C Programming Language.

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.

like image 84
kennytm Avatar answered Oct 02 '22 18:10

kennytm