Created
May 13, 2014 20:48
-
-
Save joshavant/4d1d5cb36efef813594f to your computer and use it in GitHub Desktop.
Thread-safe, forced initialization for singletons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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