Objective-C初始化(静态方法)调用了更多一次? [英] Objective-C initialize (static method) called more that once?
问题描述
SubclassOfNSObject * GlobalVariableThatShouldNeverChange;
@implementation MyClass
+(void)初始化
{
[super initialize];
GlobalVariableThatShouldNeverChange = [[SubclassOfNSObject alloc] init];
//使用GlobalVariableThatShouldNeverChange
}
@end
$ b更改更多内容$ b
我在整个代码中引用了这个参数,指向它的指针永远不会改变,因为我在代码中使用它。
问题是,当我使用 GHUnit
运行测试时,我遇到了 GlobalVariableThatShouldNeverChange
的指针被改变(即它正在重新初始化,我通过autorelease池发布的变量有问题,并且已修复,我对此问题有一个解决方法,但我想知道 为什么 ?
谢谢!
文档说:b
$ b
运行时发送初始化给程序中的每个类,恰好在该类之前,或者从该类继承的任何类它。
推荐的方法是:
+(void)初始化
{
if(self == [GHUnit class]){
/ * pu t初始化代码* /
}
}
另外请注意文档中的以下建议:
…你通常不应该在你的实现中发送
initialize
到super
。
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!
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
tosuper
in your implementation.
这篇关于Objective-C初始化(静态方法)调用了更多一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!