Skip to content

Instantly share code, notes, and snippets.

@darcyliu
Created August 18, 2012 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darcyliu/3384993 to your computer and use it in GitHub Desktop.
Save darcyliu/3384993 to your computer and use it in GitHub Desktop.
Objective-C Singleton Demo
#import <Foundation/Foundation.h>
#import "Singleton.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Objective-C Singleton Demo");
[[Singleton sharedSingleton] sayHello];
[[Singleton sharedSingleton] sayHello];
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+(Singleton*)sharedSingleton;
-(void)sayHello;
@end
#import "Singleton.h"
@implementation Singleton
static Singleton* _sharedSingleton = nil;
+(Singleton *) sharedSingleton{
@synchronized([Singleton class])
{
if (!_sharedSingleton)
[[self alloc] init];
return _sharedSingleton;
}
return nil;
}
+(id)alloc
{
@synchronized([Singleton class])
{
NSAssert(_sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton.");
_sharedSingleton = [super alloc];
return _sharedSingleton;
}
return nil;
}
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
}
return self;
}
-(void)sayHello {
NSLog(@"Hello World!");
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment