10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-C で Singleton の実装

Posted at

確か Objective-C フレーズブック に載っていた。
知っている限りで一番シンプルな実装方法。
alloc-init や new でのインスタンス化は許容していない。

document.h
#import <Foundation/Foundation.h>

@interface Document : NSObject
+ (Document*)sharedDocument;
@end
document.m
#import "Document.h"

@implementation Document

static Document* _sharedDocument;

+ (void)initialize
{
    if ([Document class] == self) {
        _sharedDocument = [self new];
    }
}

+ (Document*)sharedDocument
{
    return _sharedDocument;
}

+ (id)allocWithZone:(NSZone *)zone
{
    if (_sharedDocument && [Document class] == self) {
        [NSException raise:NSGenericException format:@"May not create more than one instance of Document."];
    }
    return [super allocWithZone:zone];
}

@end
10
10
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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?