Skip to content

Instantly share code, notes, and snippets.

@josephsieh
Forked from virasio/Singleton.h
Last active May 12, 2016 22:15
Show Gist options
  • Save josephsieh/ff763fbb7b5ac9449b8363abef26a976 to your computer and use it in GitHub Desktop.
Save josephsieh/ff763fbb7b5ac9449b8363abef26a976 to your computer and use it in GitHub Desktop.
Singleton (Objective-C with ARC)
#import <Foundation/Foundation.h>
@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];
if (self)
{
// 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