MYSingleton.h : 單例宏定義 - 頭文件
// 使用方法:.h 添加
// MYSingletonH(SingletonClass)//單例模式
// 使用方法:.m 添加
// MYSingletonM(SingletonClass)//單例模式
// MYSingletonH.h文件 - 創建MYSingletonH.h全局文件
#define MYSingletonH(name) + (instancetype)shared##name;
#if __has_feature(objc_arc)
#define MYSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) {\
_instace = [super allocWithZone:zone]; \
NSLog(@"單例創建!--- 上架刪除該行"); \
} \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
if (_instace == nil) {\
_instace = [[self alloc]init]; \
} \
return _instace; \
\
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
}
#else
#define MYSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
} \
\
- (oneway void)release { } \
- (id)retain { return self; } \
- (NSUInteger)retainCount { return 1;} \
- (id)autorelease { return self;}
#endif