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!
The docs say:
The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it.
The recommended approach is:
+ (void)initialize
{
if (self == [GHUnit class]) {
/* put initialization code here */
}
}
Also note the following recommendation from the documentation:
… you should typically not send
initialize
tosuper
in your implementation.
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)
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.
来源:https://stackoverflow.com/questions/3910187/objective-c-initialize-static-method-called-more-that-once