iOS下单例模式实现(二)利用宏定义快速实现

在上一节里提到了用利用gcd快速实现单例模式。编码

一个项目里面可能有好几个类都须要实现单例模式。为了更高效的编码,能够利用c语言中宏定义来实现。spa

新建一个Singleton.h的头文件。code

// @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”须要在前面加上 ##blog

当宏的定义超过一行时,在末尾加上“\”表示下一行也在宏定义范围内。it

注意最后一行不须要加"\”。io

 

下面就说明下在代码中如何调用:class

这个是在类的声明里:import

#import "Singleton.h"

@interface SoundTool : NSObject

// 公共的访问单例对象的方法
singleton_interface(SoundTool)

@end

这个是在类的实现文件中:gc

类在初始化时须要作的操做可在 init 方法中实现。

@implementation SoundTool

singleton_implementation(SoundTool)

- (id)init
{

}

@end
相关文章
相关标签/搜索