#define DEFINE_SINGLETON_HEADER(className) \
\
+ (className *)shared##className;
#define DEFINE_SINGLETON_IMPLEMENTATION(className) \
\
static className *shared##className = nil; \
static dispatch_once_t pred; \
\
+ (className *)shared##className { \
dispatch_once(&pred, ^{ \
shared##className = [[super allocWithZone:NULL] init]; \
}); \
return shared##className; \
} \
\
+ (id)allocWithZone:(NSZone *)zone { \
return [self shared##className];\
} \
\
- (id)copyWithZone:(NSZone *)zone { \
return self; \
}
使用如下
@interface MySingleton : NSObject
DEFINE_SINGLETON_HEADER(MySingleton);
/**other method declare**/
@end
比如
@implementation MySingleton
DEFINE_SINGLETON_IMPLEMENTATION(MySingleton)
- (instancetype)init {
if (sharedMySingleton) {
return sharedMySingleton;
}
if (self = [super init]) {
//todo init other
}
return self;
}
@end