2016-03-31 7 views
1

コードサンプル1:Objective-Cのシングルトン作成

+ (MyClass *)sharedInstance{ 
    static MyClass *sharedInstance = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     sharedInstance = [[self alloc] init]; 
    }); 
    return sharedInstance; 
} 

コードサンプル2

+ (MyClass *)sharedInstance{ 
    static MyClass *sharedInstance = nil; 
    if (!sharedInstance) { 
     sharedInstance = [[MyClass alloc] init]; 
    } 
    return sharedInstance; 
} 

上記のコードサンプルの結果に違いはありますか?

答えて

4

最初の方が、必要な状況が満たされた場合に複数のスレッドがSingletonクラスの複数のインスタンスを作成するのを防ぐので、より優れています。

例:2番目の例を参照してください。

+ (MyClass *)sharedInstance{ 
    static MyClass *sharedInstance = nil; 
    if (!sharedInstance) { 
     sharedInstance = [[MyClass alloc] init]; 
    } 
    return sharedInstance; 
} 

と仮定Theread1は、以下のLOCを実行してから実行しThread1

sharedInstance = [[MyClass alloc] init]; 

へのハンドルの上に、次のLOC、その後の手今すぐThread2

if (!sharedInstance) 

Thread2へのハンドルを提供しますif条件が最初にThread1を満たしていたので、Thread1はconti今だけでなく

sharedInstance = [[MyClass alloc] init]; 

次LOCをNUEと実行、作成MyClassの2つのインスタンスを持っています。

したがって、第1のアプローチが最適です。ブロック内にブロックがあることを確認します

dispatch_once(&onceToken, ^{ 

    }); 

は1回だけ実行されます!

ただし、メインスレッド(UIスレッド)を介してシングルトンにのみアクセスすると、2番目のシナリオも機能します。

0

dispatch_once()を使用すると、何かが一度だけ実行されるため、異なるスレッドから2回アクセスすると問題は発生しません。

+0

'dispatch_once'は' if'よりもどのように高速ですか? '@synchronized'より速いですが、2番目のコードサンプルに' @synchronized'がありません。 – FreeNickname

関連する問題