Skip to content

Instantly share code, notes, and snippets.

@situee
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save situee/305c1ec6719108682dc2 to your computer and use it in GitHub Desktop.

Select an option

Save situee/305c1ec6719108682dc2 to your computer and use it in GitHub Desktop.
objective-c singleton
// GCD using "instancetype" as return type
+ (instancetype)shared
{
static id shared;
static dispatch_once_t token;
dispatch_once(&token, ^{
shared = [[self alloc] init];
});
return shared;
}
// The following two methods are from http://www.galloway.me.uk/tutorials/singleton-classes/
// use GCD
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
// use "synchronized"
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
@synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment