views:

391

answers:

2

Is it possible to assign a value to an instance variable during an initialize class method?

I'm declaring a number of arrays, then creating an array of arrays, then assigning it to self.months, which is an instance variable. Why does this not work, and how can I accomplish this?

      +(void)initialize
 {
    // .....
        NSArray *matrix = [[NSArray alloc] initWithObjects:jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec, nil ];

    self.months = matrix;
    [matrix release]

}

+3  A: 

I think you're confused about what initialize does. It's to initialize the class itself. There is no instance, and thus there are no instance variables. To initialize an instance, override the init method.

Chuck
+3  A: 

You cannot set instance variables in class methods as you have no reference to an instance. The initialize method on a class is called the first time that class receives any messages and is meant to do any kind of global set-up that your class might need before any actual messages are processed. For example, setting up initial user defaults is typically done in the initialize method of your application's controller or delegate class.

To set up instance variables, you should do this in the object's designated initializer (this is init by default, but certain objects change the designated initializer if they need to take parameters). For example:

- (id)init {
  if( (self = [super init]) ) {
    myInstanceVariable = (int *)malloc(50 * sizeof(int));
  }
}

- (void)dealloc {
  free(myInstanceVariable);
  [super dealloc];
}

Here you actually have a reference to self which you can use because a distinct instance of an object has been allocated.

Jason Coco