Objective-C 初始化(静态方法)调用了不止一次?

发布于 2024-09-27 08:28:50 字数 578 浏览 4 评论 0原文

我在 Objective-C 中有与此类似的代码:

SubclassOfNSObject *GlobalVariableThatShouldNeverChange;

@implementation MyClass

+(void) initialize
{
    [super initialize];
    GlobalVariableThatShouldNeverChange = [[SubclassOfNSObject alloc] init];
    // Change more stuff with GlobalVariableThatShouldNeverChange
}

@end

我在整个代码中引用了 this,并且指向 this 的指针永远不应该改变,因为我在代码中的任何地方都使用它。 问题是,当我使用 GHUnit 运行测试时,我遇到了 GlobalVariableThatShouldNeverChange 指针被更改的奇怪问题(即它正在重新初始化。我遇到了问题变量通过自动释放池释放并且已修复,我有解决此问题的方法,但我想知道为什么

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冷弦 2024-10-04 08:28:50

文档说:

运行时将初始化发送到程序中的每个类,或任何继承自该类的类之前恰好一次。


推荐的方法是:

+ (void)initialize
{
    if (self == [GHUnit class]) {

        /* put initialization code here */

    }
}

另请注意文档中的以下建议:

…您通常不应在实现中将 initialize 发送到 super

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.

绳情 2024-10-04 08:28:50

简短的回答是肯定的,+initialize 可以被多次调用。

Bill Bumgarner 在他的博客上写了一篇关于此的好文章。请参阅+initialize 可以执行多次(+load 没那么多)

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)

半岛未凉 2024-10-04 08:28:50

补充一下 dreamlax 的答案:请注意,您可能有子类而没有显式创建它们,即,如果您使用 KVO,将动态创建子类(反过来将再次调用初始化),并且您的所有实例正在更改为这个类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文