IOS 宏定义一个单例

时间:2022-02-22 09:45:18

  有时候是不是因为频繁地创建一个单例对象而头疼,一种方式要写好多遍?当然你可以用OC语言进行封装。但下面将介绍一种由C语言进行的封装。只要实现下面的方法,以后建单例对象只要二句话。

  1.新建一个.h文件,在文件中实现以下方法:

 / .h
#define singleton_interface(class) + (instancetype)shared##class; // .m
#define singleton_implementation(class) \
static class *_instance; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
\
return _instance; \
} \
\
+ (instancetype)shared##class \
{ \
if (_instance == nil) { \
_instance = [[class alloc] init]; \
} \
\
return _instance; \
}

  2.如何使用。

    在想创建单例的类中的.h文件中写下第一句话:

      singleton_interface(类名)
在.m文件中写下第二句话:
      singleton_implementation(类名) 

好了,以后在任何项目中导入这个头文件后,然后在类中实现这两句话,就可以轻松地使用单例了,再也不用频繁地重复写大量的代码了。看起来是不是很高大上!