您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

用巨集快速建立 iOS 單例

編輯:iOS 相關資訊

若多個類別都需要單例,可利用 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 與類別名稱;多行巨集需用反斜線續行,最後一行不需要。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved