Last active
July 28, 2016 03:19
-
-
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.
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 <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 |
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 "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