Objective C - 什么使静态变量只初始化一次?

时间:2017-02-13 04:34:03

标签: objective-c

我来自另一种编程语言。我能理解单身模式。但是我在ObjectiveC的Singleton实施中感到困惑。

实际上,我理解静态变量的生命周期。但是什么使静态变量只初始化一次?

@implementation MyManager

+(instancetype)sharedInstance {

    // structure used to test whether the block has completed or not
    //Doubt 1 - If this method called second time, how it is not reset again to 0. How it is not executed second time?
    static dispatch_once_t p = 0;

    // initialize sharedObject as nil (first call only)
    //Doubt 2 - If this method called second time, how it is not reset again to nil, How it is not executed second time?
    __strong static MyManager * _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;
}

@end

2 个答案:

答案 0 :(得分:2)

  

在计算机编程中,静态变量是一个静态分配的变量,以便其生命周期或“范围”在整个程序运行中延伸。

https://en.wikipedia.org/wiki/Static_variable

答案 1 :(得分:1)

dispatch_once的调用只会初始化一次。

dispatch_once获取指向静态内存位置的指针。它有效地实现了以下目标:

lock location; if anyone else has locked location, block until we can
if (location is unset) {
   do_thing
   set location
}
unlock location

但它以更快的方式实现这一点,并不需要真正的锁定(它需要一个特殊的CPU指令,但是,称为"比较和交换。")如果你想要更多详情,请参阅Mike Ash's excellent explanation。但对于大多数用途,您可以接受dispatch_once,如果使用正确,每次执行程序时只运行一次。