Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save linearhw/44ea3a79136aa45f1fdc22696136ca48 to your computer and use it in GitHub Desktop.
Save linearhw/44ea3a79136aa45f1fdc22696136ca48 to your computer and use it in GitHub Desktop.
Effective Objective-C 45

싱글턴 디자인 패턴은 흔히 사용되는 패턴이지만 thread-safety 에 대한 논쟁이 있다.
그래서 동기화 블록으로 둘러쌓기도 한다.

+ (id) sharedInstance {
    static EOCClass *sharedInstance = nil;
    @synchronized(self) {
        if (!sharedInstance) {
            sharedInstance = [[self alloc] init];
        }
    }
    return sharedInstance;
}

하지만 dispatch_once 라는 함수를 쓰면 훨씬 쉽게 구현할 수 있다.

// 토큰을 이용해서 블록이 (thread-safe 이면서 한 번만) 실행된다는 걸 보장한다.
// 물론 그러려면 항상 같은 토큰을 사용해야 한다. 즉 static 이나 global 로 선언해야 한다.
// synchronized 보다 훨씬 빠르다. 

void dispatch_once(dispatch_once_t *token, 
                   dispatch_block_t block);
    
+ (id) sharedInstance {
    static EOCClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment