在上一节里提到了用利用gcd快速实现单例模式。
一个项目里面可能有好几个类都需要实现单例模式。为了更高效的编码,可以利用c语言中宏定义来实现。
新建一个Singleton.h的头文件。
// @interface
#define singleton_interface(className) \
+ (className *)shared##className; // @implementation
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (className *)shared##className \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}
这里假设了实例的分享方法叫 shared"ClassName".
因为方法名 shared"ClassName"是连在一起的,为了让宏能够正确替换掉签名中的“ClassName”需要在前面加上 ##
当宏的定义超过一行时,在末尾加上“\”表示下一行也在宏定义范围内。
注意最后一行不需要加"\”。
下面就说明下在代码中如何调用:
这个是在类的声明里:
#import "Singleton.h" @interface SoundTool : NSObject // 公共的访问单例对象的方法
singleton_interface(SoundTool) @end
这个是在类的实现文件中:
类在初始化时需要做的操作可在 init 方法中实现。
@implementation SoundTool singleton_implementation(SoundTool) - (id)init
{ } @end