The Pragmatic Ball boy

iOSを中心にやってる万年球拾いの老害エンジニアメモ

Objective-Cのシングルトンパターン

Objective-Cのシングルトンの実装ですが、
GCDにdispatch_onceという便利なのがあるので、これを利用するとすっきり書けますし、dispatch_onceだとXcodeによる補完が強力なので書くのも速いです。
http://stackoverflow.com/questions/7568935/how-do-i-implement-an-objective-c-singleton-that-is-compatible-with-arc


+ (MyClass *)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;


    dispatch_once(&onceToken;, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}