I have code similar to this in Objective-C:
SubclassOfNSObject *GlobalVariableThatShouldNeverChange;
@implementation MyClass
+(void) initialize
{
[super initialize];
GlobalVariableThatShouldNeverChange = [[SubclassOfNSObject alloc] init];
// Change more stuff with GlobalVariableThatShouldNeverChange
}
@end
I have this referenced throughout code, and the pointer to this should never change because I am using it everywhere through my code.
The problem is, that when I run my tests using GHUnit
, I have odd problems with the GlobalVariableThatShouldNeverChange
's pointer being changed (i.e. It is being reinitialized. I had a problem with the variable being released via the autorelease pool and that is fixed, and I have a workaround for this problem, but I would like to know why?
Thank you!
To add up on dreamlax' answer: Beware that you might have subclasses without explicitly creating them, i.e. if you are using KVO, a subclass will be created on-the-fly (which in turn will call initialize again), and all your instances are being changed to this very class.
The docs say:
The recommended approach is:
Also note the following recommendation from the documentation:
The short answer is yes,
+initialize
can be called more than once.Bill Bumgarner wrote up a good article on his blog about this. See +initialize Can Be Executed Multiple Times (+load not so much)