Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C initialize (static method) called more that once?

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!

like image 294
Richard J. Ross III Avatar asked Oct 11 '10 21:10

Richard J. Ross III


3 Answers

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 to super in your implementation.

like image 139
dreamlax Avatar answered Sep 20 '22 21:09

dreamlax


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)

like image 32
Jay O'Conor Avatar answered Sep 20 '22 21:09

Jay O'Conor


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.

like image 21
DrMickeyLauer Avatar answered Sep 22 '22 21:09

DrMickeyLauer