iOS中的Singleton

cip*_*erz 1 singleton ios

我试图理解为什么dinpatch_once_t和_sharedObject在重复调用sharedInstance时分别没有设置为0和nil的原因.在我看来,这是编码的方式,局部变量将重新初始化,因为你可以重置一个静态值,对吧?我在这里不了解ARC或iOS内存管理的基本内容?

+ (id)sharedInstance
{
// structure used to test whether the block has completed or not
static dispatch_once_t p = 0;

// initialize sharedObject as nil (first call only)
__strong static id _sharedObject = nil;

// executes a block object once and only once for the lifetime of an application
dispatch_once(&p, ^{
    _sharedObject = [[self alloc] init];
});

// returns the same object each time
return _sharedObject;
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*lls 7

它实际上是一个C而不是ARC或iOS.它是一个"内部静态变量"(也就是局部静态变量),它的声明只处理一次.它具有功能本地的范围,但延长了寿命.