Click here to Skip to main content
15,880,651 members
Articles / Mobile Apps / iPhone
Tip/Trick

Implement Singleton Pattern in Objective-C

Rate me:
Please Sign up or sign in to vote.
4.69/5 (7 votes)
12 Dec 2013CPOL 36.3K   6  
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)


Written By
Architect SIS
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)

Comments and Discussions

 
-- There are no messages in this forum --