私は別のプログラミング言語を使いました。私はシングルトンパターンを理解することができます。しかし、私はObjectiveCのSingleton Implementationを混乱させました。目的C - 静的変数を1回だけ初期化しますか?
実際、私は静的変数の有効期間を理解しています。しかし、なぜ静的変数を1回だけ初期化するのですか?コンピュータプログラミングにおいて
@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
静的変数のみが一度初期化されます。それを簡単に確認することができます。おそらく他のいくつかの質問に重複しています。あなたの質問を明確に述べてください。私はそれを読んでいるほとんどの人が他の人のコメントに隠された質問を逃すだろうと思う。 –
あなたの混乱は 'static'キーワードの周りを回っているようだ。目的CはC言語から継承し、まったく同じように動作します。 http://stackoverflow.com/a/572550/3141234 – Alexander
ここをクリックhttp://stackoverflow.com/a/16208466/3110026 –