iOS开发中单例模式宏,在MRC和ARC通用

『导言』

亲们!有木有遇到这种情况:在iOS开发中多处用到单例模式,比如:多处处理网络请求况下,这时候难道不停地写单例模式?其实呀,有更好办法,建立一个宏文件,只要拖入工程,任何情况下套用都行!

一 、单例宏文件代码如下:单例宏Sing.h下载
#define SingleH(name)   +(instancetype )share##name;

//条件满足ARC
# if __has_feature(objc_arc)
//否则执行MAC  ##表示拼接   条件编译if不能放入宏define,所以先条件编译大与宏范围。

#define SingleM(name)   static  id  _instance; \
+(instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{   \
_instance = [super allocWithZone: zone]; \
});  \
return _instance; \
} \
\
+(instancetype )share##name   \
{ \
return [[self alloc] init ]; \
} \
\
-(id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
\
-(id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \

# else
//条件不满足:MRC
#pragma mark - MRC

#define SingleM(name)   static  id  _instance; \
+(instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{   \
_instance = [super allocWithZone: zone]; \
});  \
return _instance; \
} \
\
+(instancetype )share##name \
{ \
return [[self alloc] init ]; \
} \
\
-(id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
\
-(id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
-(oneway void)release \
{ \
  \
} \
-(instancetype)retain \
{ \
 \
return _instance;  \
} \
-(NSUInteger)retainCount \
{ \
    return MAXFLOAT; \
}//不能加\   如果加表示endif 为MRC其中的一部风

# endif
二、如何套用?demo下载

1.0 将宏下载下来,拖入xcode工程中.
2.0 比如:建立一个继承NSObject的ZWJTool.h ZWJTool.m文件
3.0 加入头文件 #import "Single.h"
4.0 在.h文件引用SingleH(ZWJTool)
5.0 在.m文件引用SingleM(ZWJTool)
6.0 在需要地方调用: ZWJTool *tool = [ZWJTool shareZWJTool];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容