Skip to content

Instantly share code, notes, and snippets.

@adison
Last active August 29, 2015 14:05
Show Gist options
  • Save adison/619a62087d3e38d164af to your computer and use it in GitHub Desktop.
Save adison/619a62087d3e38d164af to your computer and use it in GitHub Desktop.
Singleton Macro, with
/*
no need to copy this section.
ussge:
in CustomClass.h
+(instancetype)sharedManager;
in CustomClss.m
@implementation CustomClass
...
SYNTHESIZE_SINGLETON_FOR_CLASS(CustomClass)
...
@end
*/
// source from http://www.tuicool.com/articles/7RZjqm
// and modified to +(instancetype)shareManager for common use
#if __has_feature(objc_arc) // ARC Version
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
+ (instancetype)sharedManager\
{\
static classname *shared##classname = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
shared##classname = [[classname alloc] init];\
});\
return shared##classname;\
}
#else // Non-ARC Version
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
static classname *shared##classname = nil; \
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [[self alloc] init]; \
} \
} \
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
return nil; \
} \
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
} \
- (id)retain \
{ \
return self; \
} \
- (NSUInteger)retainCount \
{ \
return NSUIntegerMax; \
} \
- (oneway void)release \
{ \
} \
- (id)autorelease \
{ \
return self; \
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment