单例宏

使用方法:

  1. 声明了两个宏 SingleH(name) 和 SingleM(name) 两个宏
  2. 创建一个想要实现单例模式的类.在.h文件中包含单例宏文件
    #import<single.h>
  3. 在.h文件中使用SingleH(name)宏
    #import <Foundation/Foundation.h>
    #import <Single.h>
    @interface CustomClass : NSObject
    SingleH();
    @end
  4. 在.m文件中使用SingleM(name)宏
    #import "CustomClass.h"
    @implementation CustomClass
    SingleM(customClass);
    @end

Single.h 文件

#define SingleH(name) +(instancetype)share##name;

#if __has_feature(objc_arc)
//条件满足 ARC
#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
#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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文首先实现单例模式,然后对单例代码进行抽取宏,使其他类可以一句代码实现单例(只介绍ARC环境)本文代码[http...
    王技术阅读 1,140评论 2 16
  • 单例模式 单例的目的:希望对象只创建一个单例,并且提供一个全局的访问点 单例模式(arc) +(instancet...
    三岁就很乖阅读 534评论 0 0
  • 单例模式 单例模式(arc) 类的实现 调用单例 单例模式(mrc) 除了上边的方法我们在mrc的时候还需要增加一...
    董军1990阅读 3,493评论 11 35
  • 你说我俩很有默契,确实,一个从不掩饰,一个从不揭穿,何处笙歌繁华落,此生无分缘寂灭!
    李景雲阅读 223评论 0 0
  • 请善待你的boss。boss就像一颗大树的根,他强壮,有力。他为你提供了养料和舞台,当你在风中翩翩起舞接受阳光的照...
    米衙阅读 258评论 0 2