Skip to content

Instantly share code, notes, and snippets.

@joshavant
Created May 13, 2014 20:48
Show Gist options
  • Save joshavant/4d1d5cb36efef813594f to your computer and use it in GitHub Desktop.
Save joshavant/4d1d5cb36efef813594f to your computer and use it in GitHub Desktop.
Thread-safe, forced initialization for singletons
#import "Foo.h"
static dispatch_once_t FooSharedDispatchOnceToken;
static Foo *FooSharedInstance;
+ (void)prepareService
{
[self fetchSharedServiceAndInitialize:YES];
}
+ (Foo *)sharedInstance {
return [self fetchSharedServiceAndInitialize:NO];
}
+ (Foo *)fetchSharedServiceAndInitialize:(BOOL)initialize
{
dispatch_once(&FooSharedDispatchOnceToken, ^{
NSAssert(initialize, @"%s: Instance must be initialized with +prepareService!", __PRETTY_FUNCTION__);
FooSharedInstance = [[self alloc] init];
// other initialization logic
});
return FooSharedInstance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment