Skip to content

Instantly share code, notes, and snippets.

@janodev
Last active July 28, 2016 03:19
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/5422015 to your computer and use it in GitHub Desktop.
Save janodev/5422015 to your computer and use it in GitHub Desktop.
Singleton pattern with __atribute__ unavailable to prevent the accidental misuse of a singleton. Note that the user is still able to create more instances using runtime functions.
#import <Foundation/Foundation.h>
@interface MySingleton : NSObject
+(instancetype) sharedInstance;
// clue for improper use (produces compile time error)
+(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
#import "MySingleton.h"
@implementation MySingleton
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype) initUniqueInstance {
return [super init];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment