+initialize (was Re: Trying to understand -- please help...)
+initialize (was Re: Trying to understand -- please help...)
- Subject: +initialize (was Re: Trying to understand -- please help...)
- From: Jason Stephenson <email@hidden>
- Date: Wed, 21 May 2008 15:00:53 -0400
Vijay Malhan wrote:
What exactly do you mean by initializing the *class*? what exactly
is initialized with +initialize() method?
When exactly this method gets called?
If you are at all familiar with Java, this is the same thing as a static
initializer.
It sets up data required by the class and all of its instances. It is
called as soon as the class exists and before the first instance is init'd.
It is often used to setup class-wide variables. As an example, I have a
Monte Carlo simulator class called Die. I can initialize any number of
Die objects, and I can set the number of "sides" of these Die objects
(dice) to any arbitrary number. In my implementation, I use the standard
library rand() function to generate pseudo-random numbers. I also
decided that all Die objects would share the same seed value. Therefore,
I made the seed a static variable with file scope in the Die.m file,
thus limiting its visibility to my Die class. I use the following class
initializer function to put a value in the seed class variable:
+(void) initialize
{
static BOOL initialized = NO;
if (NO == initialized) {
time((time_t *)&seed);
initialized = YES;
}
}
Thus, the +initialize method is used to setup one-time things that you
need to happen for the class as a whole and not for individual instances
of the class.
HtH,
Jason
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden