9
8

More than 5 years have passed since last update.

[Cocoa]Singleton

Last updated at Posted at 2015-12-31

大晦日になって、自分が知らなかったことに気がついてしまった。

マルチスレッドの環境でシングルトンを実装する場合、ロックが思っていたが、Swiftでは状況が異なるようだ。

Objective-Cで実装する場合、以下の通り。

+ (instancetype)sharedInstance {
    static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });

    return _sharedInstance;
}

Swiftだとstatic変数はクラスアクセス時に生成されるので、以下のように記述できる。

class Singleton {
    static let sharedInstance = Singleton()
}

シングルトンなインスタンス生成時に設定が必要な場合は以下となる。

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}

もし、シングルトン以外のインスタンス生成を許したくない場合は、C++でコンストラクタをpriateにするのと同様に、privateなinit()関数を用意すればいい。

    private init() {
        // setup code
    }

関連情報
Using Swift with Cocoa and Objective-C (Swift 2.1)

【Cocoa練習帳】
http://www.bitz.co.jp/weblog/

http://ameblo.jp/bitz/(ミラー・サイト)

Qiita

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8