Click here to Skip to main content
Click here to Skip to main content

Tagged as

Implement Singleton Pattern in Objective-C

, 12 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

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

Comments and Discussions

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