忘備録

日々の調べ物をまとめる。アウトプットする。基本自分用。

【Objective-C】シングルトン

ARCという前提で...

Singleton.h

#import <Foundation/Foundation.h>

@interface Singleton : NSObject

/**
 インスタンス生成ファクトリメソッド
 @return Singletonクラスのインスタンス
 */
+ (Singleton*)sharedManager;

@end

Singleton.m

#import "Singleton.h"

@implementation Singleton

static Singleton *sharedInstance = nil;

+ (Singleton *)sharedManager
{
    // dispatch_once_t を利用することでインスタンス生成を1度に制限できる
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Singleton alloc] init];
    });
    return sharedInstance;
}

/**
 外部からallocされた時のためにallocWithZoneをオーバーライドして、
 一度しかインスタンスを返さないようにする
 */
+ (id)allocWithZone:(NSZone *)zone {
    
    __block id ret = nil;
    
    static dispatch_once_t once;
    dispatch_once( &once, ^{
        sharedInstance = [super allocWithZone:zone];
        ret = sharedInstance;
    });
    
    return  ret;
}

/**
 copyで別インスタンスが返されないようにするため
 copyWithZoneをオーバーライドして、自身のインスタンスを返すようにする。
 */
- (id)copyWithZone:(NSZone *)zone{
    
    return self;
}

@end

参考

Objective-CのSingleton、その歴史的経緯など