Skip to content

Instantly share code, notes, and snippets.

@chris-erickson
Created June 9, 2013 23:04
Show Gist options
  • Save chris-erickson/5745636 to your computer and use it in GitHub Desktop.
Save chris-erickson/5745636 to your computer and use it in GitHub Desktop.
This is a preferred way to set up a singleton.
#import <Foundation/Foundation.h>
@interface SingletonClass : NSObject
{
}
// Properties of the singleton
+(SingletonClass *)sharedSingleton;
@end
#import "SingletonClass.h"
@implementation SingletonClass
static SingletonClass *theSingleton = nil;
+(SingletonClass *)sharedSingleton {
if (theSingleton != nil) {
return theSingleton;
}
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
theSingleton = [[SingletonClass alloc] init];
});
return theSingleton;
}
// Called the first time the Singleton is used
- (id)init
{
self = [super init];
if (self) {
// Post initialization code such as setting other properties
}
return self;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment