一个项目里面可能有好几个类都需要实现单例模式。为了更高效的编码,可以利用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
本文介绍如何利用宏定义在Objective-C中高效创建单例对象,通过Singleton.h头文件,定义共享实例方法shared"ClassName",并提供在类声明和实现文件中的调用方式,以简化单例模式的实现。
606

被折叠的 条评论
为什么被折叠?



