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

那年仲夏 提交于 2019-12-21 12:08:51

问题


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!


回答1:


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.




回答2:


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)




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!