Singleton

On 2010年9月14日, in Objective-C, by タカ
Share on Facebook

比較的よく使うのでメモとしてエントリー


Singleton.h

#import <Foundation/Foundation.h>
@interface Singleton : NSObject {

}
+ (id)instance;

Singleton.m

@implementation Singleton

static id _instance = nil;

+ (id)instance
{
    @synchronized(self) {
        if (!_instance) {
            [[self alloc] init];
        }
    }
    return _instance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (!_instance) {
            _instance = [super allocWithZone:zone];
            return _instance;
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (unsigned)returnCount
{
    return UINT_MAX;
}

- (void)release
{
}

- (id)autorelease
{
    return self;
}

@end

One Response to Singleton

  1. [...] Singleton(dispatch_once版) On 2011年12月1日, in Objective-C, by タカ Objective-Cのシングルトンは以前書いたけど、 [...]

コメントを残す

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt="">