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

3

7

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!

Cayuga answered 11/10, 2010 at 21:46 Comment(0)
P
16

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.

Parlin answered 11/10, 2010 at 21:55 Comment(2)
Ok, so I forgot the self == Superclass, thank you! And do you have to have [super initialize]?Cayuga
That is interesting, I did not know that. It also means a superclass can actually find out at run-time which sub-classes it has.Decrescent
A
6

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)

Aglitter answered 11/10, 2010 at 21:56 Comment(1)
Ok..I was not doing any heavy lifting, only allocating global variables..thank you, it has taught me a lot!Cayuga
P
2

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.

Pyrogenous answered 18/1, 2012 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.