在上一節裏提到了用利用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