gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:34:38 26 4
gpt4 key购买 nike

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

SubclassOfNSObject *GlobalVariableThatShouldNeverChange;

@implementation MyClass

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

@end

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

谢谢!

最佳答案

docs说:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it.

推荐的方法是:

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

/* put initialization code here */

}
}

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

… you should typically not send initialize to super in your implementation.

关于Objective-C 初始化(静态方法)调用了不止一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3910187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com