iOS 宏定义单例模式

使用方法:
  • 1, 创建一个头文件,然后黏贴如下代码

//条件编译
#if __has_feature(objc_arc)
    //ARC


//.h头文件中的单例宏
#define IMSingletonH(name) + (instancetype)shared##name;

//.m文件中的单例宏
#define IMSingletonM(name) \
static id _instance;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+ (instancetype)shared##name{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}



#else
    //MRC


//.h头文件中的单例宏
#define IMSingletonH(name) + (instancetype)shared##name;

//.m文件中的单例宏
#define IMSingletonM(name) \
static id _instance;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+ (instancetype)shared##name{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
- (oneway void)release{\
}\
- (instancetype)retain{\
    return self;\
}\
- (NSUInteger)retainCount{\
    return 1;\
}\
- (instancetype)autorelease{\
    return self;\
}



#endif
  • 2,在使用的时候只需要引入这个头文件,然后在使用的那个头文件和.m文件中各添加一句代码即可,如下:
//注意下面括号中的内容是你在用单例模式的时候显示的名字,如sharedPlayer;
//IMMusicPlayer *player03 = [IMMusicPlayer sharedPlayer];

//头文件中
IMSingletonH(Player)

//.m文件中:
IMSingletonM(Player)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,216评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,337评论 19 139
  • 简简单单的上班下班,做好自己的工作。 至真至纯,如花美梦。
    地六藏之阅读 1,839评论 1 1
  • Android coverage with Appiumappium client capabilities: +...
    Lacia阅读 1,872评论 0 0
  • 感觉越长大时间过得越快,转眼2017年已经过去一半了。时间车轮滚滚向前,自己的年龄也逐年增加,最明显的特征是再也不...
    亦书欢言阅读 3,567评论 3 2