65.9K
CodeProject is changing. Read more.
Home

Implement Singleton Pattern in Objective-C

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.69/5 (7 votes)

Jul 27, 2011

CPOL
viewsIcon

36570

Implement Objective-C Singleton Pattern

Introduction

I will demo how to implement Singleton pattern with Objective-C.

MySingleton.h
#import 
 
@interface MySingleton : NSObject {
 
}
+(MySingleton*)sharedMySingleton;
-(void)test;
@end
MySingleton.m
@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;
 
+(MySingleton*)sharedMySingleton
{
    @synchronized([MySingleton class])
    {
        if (!_sharedMySingleton)
            [[self alloc] init];
 
        return _sharedMySingleton;
    }
 
    return nil;
}
 
+(id)alloc
{
    @synchronized([MySingleton class])
    {
        NSAssert(_sharedMySingleton == nil, 
          @"Attempted to allocate a second instance of a singleton.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }
 
    return nil;
}
 
-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }
 
    return self;
}
 
-(void)test {
    NSLog(@"Hello World!");
}
@end