Skip to content

Instantly share code, notes, and snippets.

@ManWithBear
Created December 22, 2016 11:22
Show Gist options
  • Save ManWithBear/92775d66a4e7e8512375f1e6a733eba6 to your computer and use it in GitHub Desktop.
Save ManWithBear/92775d66a4e7e8512375f1e6a733eba6 to your computer and use it in GitHub Desktop.
Registry pattern for singleton factory
+ (instancetype)sharedInstance {
static dispatch_once_t once;
static NSMutableDictionary *sharedInstances;
dispatch_once(&once, ^{
// Creating of the container for shared instances for different classes
sharedInstances = [NSMutableDictionary new];
});
id sharedInstance = nil;
@synchronized(self) { /* Critical section for Singleton-behavior */
// Getting of the shared instance for exact class
sharedInstance = sharedInstances[NSStringFromClass(self)];
if (!sharedInstance) {
// Creating of the shared instance if it's not created yet
sharedInstance = [self new];
sharedInstances[NSStringFromClass(self)] = sharedInstance;
}
}
return sharedInstance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment