Skip to content

Instantly share code, notes, and snippets.

@623637646
Last active April 11, 2019 03:48
Show Gist options
  • Save 623637646/4cfd8eadb0665f194f88e97879784d82 to your computer and use it in GitHub Desktop.
Save 623637646/4cfd8eadb0665f194f88e97879784d82 to your computer and use it in GitHub Desktop.
iOS Objective-C Singleton with Macro!!!
#define MACRO_SINGLETON_H \
+ (instancetype)sharedInstance;\
- (instancetype)init NS_UNAVAILABLE;\
+ (instancetype)new NS_UNAVAILABLE;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone NS_UNAVAILABLE;\
- (id)copy NS_UNAVAILABLE;\
- (id)mutableCopy NS_UNAVAILABLE;\
+ (id)copyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE;\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone NS_UNAVAILABLE;\
#define MACRO_SINGLETON_M(MACRO_SINGLETON_INTT)\
static id _instance;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+ (instancetype)sharedInstance\
{\
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}\
- (id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
- (id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
- (instancetype)init\
{\
self = [super init];\
if (self) {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
MACRO_SINGLETON_INTT\
});\
}\
return self;\
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment