Skip to content

Latest commit

 

History

History
45 lines (34 loc) · 1.51 KB

how-to-create-singleton.md

File metadata and controls

45 lines (34 loc) · 1.51 KB

シングルトンオブジェクトの作成方法

dispatch_onceを使った方法。

// SingletonObject.h
@interface SingletonObject: NSObject
+ (SingletonObject*)sharedSingletonObject;
@end
// SingletonObject.m
@implementation SingletonObject
static SingletonObject* _instance = nil;

+ (SingletonObject*) sharedSingletonObject {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        _instance = [SingletonObject new];
    });
    return = _instance;
}
@end

sharedSingletonObject()のメソッドスコープ中にstaticつけたローカル変数書くだけでも期待した挙動させられるよ的な文言を見た気がするけど思い出せない。

できる? できないってコンパイラに怒られた

+(SingletonObject*)sharedSingletonObject {
    static SingletonObject* _instance = [SingletonObject new];
    return _instance;
}

C言語の文脈からすればstatic修飾子のついた行は一度しか実行されないから、とかなんとか聴いた気がする… もしくはXcodeがコンパイル時にdispatch_once形式に実は変えちゃうんだよねーとかなんとか…

うろ覚えで書いたコードは動かなかったしdispatch_once形式のほうが明確だからそれでいいや