单例宏的使用

2019-12-25  本文已影响0人  Flynn_Lee

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方法

上一篇 下一篇

猜你喜欢

热点阅读