若多個類別都需要單例,可利用 C 語言巨集減少重複程式碼。以下以 dispatch_once 實作 thread-safe 單例。
#define singleton_interface(className) \
+ (className *)shared##className;
#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; \
}
使用時,在標頭檔寫入 singleton_interface(SoundTool),在實作檔寫入 singleton_implementation(SoundTool)。若初始化需要額外設定,可在 init 方法中處理。
注意 ## 用於讓巨集拼接 shared 與類別名稱;多行巨集需用反斜線續行,最後一行不需要。