Skip to content

Instantly share code, notes, and snippets.

@pingwinator
Forked from virasio/Singleton.h
Created February 2, 2017 17:58
Show Gist options
  • Save pingwinator/584b916488c7b4b6bf877dcab987fd63 to your computer and use it in GitHub Desktop.
Save pingwinator/584b916488c7b4b6bf877dcab987fd63 to your computer and use it in GitHub Desktop.
Singleton (Objective-C with ARC)
@interface MySingleton : NSObject
// ...
+ (instancetype) sharedInstance;
+ (instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
- (instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+ (instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));
// ...
@end
@implementation MySingleton
// ...
+ (instancetype) sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[super alloc] initInstance];
});
return sharedInstance;
}
- (instancetype) initInstance {
self = [super init];
// Do any other initialisation stuff here
// ...
return self;
}
// ...
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment