Objective-C 初始化(静态方法)调用了不止一次?
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
文档说:
推荐的方法是:
另请注意文档中的以下建议:
The docs say:
The recommended approach is:
Also note the following recommendation from the documentation:
简短的回答是肯定的,
+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)
补充一下 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.