Click here to Skip to main content
11,707,167 members (55,422 online)
Click here to Skip to main content

Tagged as

Implement Singleton Pattern in Objective-C

, 12 Dec 2013 CPOL 22.5K 6
Rate this:
Please Sign up or sign in to vote.
Implement Objective-C Singleton Pattern


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

@interface MySingleton : NSObject {
@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;
    @synchronized([MySingleton class])
        if (!_sharedMySingleton)
            [[self alloc] init];
        return _sharedMySingleton;
    return nil;
    @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!");


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


About the Author

Cloud Hsu
Architect LPI
Taiwan Taiwan
CloudBox cross-platform framework. (iOS+ Android)
Github: cloudhsu
1. Super Baby Pig (iOS+Android)
2. God Lotto (iOS+Android)
2. Ninja Darts (iOS)
3. Fight Bingo (iOS)

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 12 Dec 2013
Article Copyright 2011 by Cloud Hsu
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid