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]
}
You cannot set instance variables in class methods as you have no reference to an instance. The
initializemethod 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 theinitializemethod 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
initby default, but certain objects change the designated initializer if they need to take parameters). For example:Here you actually have a reference to
selfwhich you can use because a distinct instance of an object has been allocated.