【问题标题】:Objective C - What makes a static variable initialize only once?Objective C - 是什么让静态变量只初始化一次?
【发布时间】:2017-07-01 00:08:25
【问题描述】:

我来自另一种编程语言。我可以理解单例模式。但是我对 ObjectiveC 的单例实现感到困惑。

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

@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

【问题讨论】:

  • 静态变量只被初始化一次。您可以轻松验证它。可能与其他问题重复。请清楚说明您的问题。我敢打赌,大多数阅读它的人会错过隐藏在其他人的 cmets 中的问题..
  • 您的困惑似乎围绕着static 关键字。 Objective C 继承自 C 语言,其行为完全相同。 stackoverflow.com/a/572550/3141234

标签: objective-c


【解决方案1】:

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

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

【讨论】:

  • 实际上,我了解静态变量的生命周期。但我的疑问是“是什么让静态变量只初始化一次?”。在stackoverflow.com/questions/5567529/… 被清除
  • @particle 您的问题得到解答了吗?如果是,请接受其中一个答案。
  • 谢谢,我知道了。
【解决方案2】:

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,如果使用正确,每次执行程序只会运行一次。

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多