【发布时间】: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