Macro单例
// .h文件的实现
#define SingletonH(methodName) + (instancetype)shared##methodName;
// .m文件实现
#if __has_feature(objc_arc) // ARC下
#define SingletonM(methodName)\
static id _instance = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
if (!_instance) {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
}\
return _instance;\
}\
\
- (instancetype)init{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super init];\
});\
return _instance;\
}\
\
+ (instancetype)share##methodName{\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)copyWithZone:(struct _NSZone *)zone {\
return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone {\
return _instance;\
}
#else
// 非ARC下
#define SingletonM(methodName)\
static id _instance = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
if (!_instance) {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
}\
return _instance;\
}\
\
- (instancetype)init{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super init];\
});\
return _instance;\
}\
\
+ (instancetype)share##methodName{\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)copyWithZone:(struct _NSZone *)zone {\
return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone {\
return _instance;\
}\
- (oneway void)release{\
\
}\
\
- (instancetype)retain{\
return self;\
}\
\
- (NSUInteger)retainCount{\
return 1;\
}
#endif
网友评论