Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / iPhone

Implement Singleton Pattern in Objective-C

4.69/5 (7 votes)
12 Dec 2013CPOL 36.6K  
Implement Objective-C Singleton Pattern

Introduction

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

MySingleton.h
Objective-C
#import 
 
@interface MySingleton : NSObject {
 
}
+(MySingleton*)sharedMySingleton;
-(void)test;
@end
MySingleton.m
Objective-C
@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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)