1、单例宏代码块如下:
#define singleH(name) +(instancetype)share##name;
#if __has_feature(objc_arc)
#define singleM(name) static id _instace;\
\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instace = [super allocWithZone:zone];\
});\
return _instace;\
}\
\
+(instancetype)share##name\
{\
return [[flynn##name alloc]init];\
}\
\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instace;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instace;\
}
#else
#define singleM(name) static id _instace;\
\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instace = [super allocWithZone:zone];\
});\
return _instace;\
}\
\
+(instancetype)share##name\
{\
return [[flynn##name alloc]init];\
}\
\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instace;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instace;\
}\
-(oneway void)release\
{\
}\
-(instancetype)retain\
{\
return _instace;\
}\
-(NSUInteger)retainCount\
{\
return MAXFLOAT;\
}
#endif
2、使用方法
第一步将代码块拷到你的pch文件中
第二步将代码中所有的flynn替换成你的类前缀。
第三步在需要使用单例的类中使用(
A、在.h文件中使用singleH(类名去除前缀部分)如:FLYNNtest,single(test)。
B、在.m文件中使用singleH(类名去除前缀部分)
第四步使用直接用类名调用share方法
网友评论