LoginSignup
18
19

More than 5 years have passed since last update.

Objective-Cでシングルトンなインスタンスを生成

Posted at

GCDのdispatch_once関数を使って下記の様に書きます。
dispatch_onceの引数に渡したブロックはアプリケーションスコープで1度のみ実行されることが保証されるとのこと。

SingletonSample.h
@interface SingletonSample : NSObject
+ (instancetype)sharedInstance;
@end

SingletonSample.m
+ (instancetype)sharedInstance
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    return instance;
}
18
19
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
18
19