在目标C中,单例设计模式的通常实现包含“静态ID theInstance = nil".在某种程度上,为什么不在外面? [英] In Objective C, Usual implementation of singleton design pattern contains "static id theInstance = nil" in a method, why not outside?
问题描述
当我在目标C中进行Singleton设计模式时,我发现很多人使用下面的代码来创建它.
When i was going through Singleton design pattern in Objective C, I found lot of people using the below code to create it.
@interface Base : NSObject {}
+(id)instance;
@end
@implementation Base
+(id) instance
{
static id theInstance = nil;
if (theInstance == nil)
{
theInstance = [[self alloc] init];
}
return theInstance;
}
@end
在这里,我没有得到为什么我们必须在方法中将静态变量分配为nil的原因,而是可以在方法外部声明该静态变量并将其分配为nil. 因为每次调用此+ instance()方法,Instance变量都将分配为nil. 它会不会失去它所指向的先前对象吗?
Here i did not get the why do we have to assign the static variable to nil in a method instead it can be declared outside the method and assigned to nil. Because everytime this +instance() method is called, theInstance variable will be assigned to nil. Will it not lose its previous object to which it was pointing to?
我尝试调试它,令人惊讶的是,调用+ instance()方法时,它不会指向nil. 谁能解释我这里发生了什么事?
I have tried debugging it, surprisingly , it will not point to nil when +instance() method is called. Can anyone explain me whats happening here?
推荐答案
static
变量仅初始化一次,而不管它们是全局范围还是局部范围.在这种情况下,甚至不需要nil
-static
存储类变量默认情况下为零初始化.声明:
static
variables only get initialized once, regardless of if they're at global or local scope. In this case, you don't even need the nil
- static
storage class variables are zero-initialized by default. This declaration:
static id theInstance;
足以与您所拥有的保持一致.
is enough to be the same as what you have there.
这篇关于在目标C中,单例设计模式的通常实现包含“静态ID theInstance = nil".在某种程度上,为什么不在外面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!