單例是 iOS 開發裡最常被使用的設計模式之一,從 NSNotificationCenter 到 NSUserDefaults,幾乎到處都是。本文從原理出發,示範如何保證「永遠只有一個物件」,最後再把它抽成可重複使用的巨集。
簡單說:同一個類別,无论你呼叫多少次,拿到的永遠是同一個物件,也就是只能被實例化一次。
物件的誕生必然經過 alloc(內部會呼叫 allocWithZone:)。因此只要攔住這一步,確保它只執行一次、並且是執行緒安全的,再把物件放在靜態區域,之後不論是 alloc、copy 都直接回傳這個實例即可。
@synchronized 或 GCD 的 dispatch_once,後者效能更好、寫法更乾淨@implementation myManager
static id instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
// 寫法一:互斥鎖
// @synchronized (self) {
// if (instance == nil) { instance = [super allocWithZone:zone]; }
// }
// 寫法二:GCD,保證只執行一次(推薦)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (instance == nil) { instance = [super allocWithZone:zone]; }
});
return instance;
}
+ (instancetype)sharedSoundTools {
instance = [[self alloc] init];
return instance;
}
- (id)copyWithZone:(NSZone *)zone { return instance; }
#pragma mark - MRC 相關
- (oneway void)release { /* 什麼都不做 */ }
- (instancetype)retain { return instance; }
- (instancetype)autorelease { return instance; }
- (NSUInteger)retainCount { return ULONG_MAX; } // 避免被誤 release 到崩潰
- (instancetype)init {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
self = [super init];
if (self) { self.age = 10; }
});
return self;
}
@end
把下面的內容存成 singleton.h,使用時只要引入這個標頭檔即可。
用法:.h 中寫 singletonInterface(myManager);,.m 中寫 singletonImplementation(myManager);。
#define singletonInterface(className) + (instancetype)shared##className;
#if __has_feature(objc_arc)
// ARC 版本
#define singletonImplementation(className) \
+ (instancetype)allocWithZone:(struct _NSZone *)zone { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
if (instance == nil) { instance = [super allocWithZone:zone]; } \
}); \
return instance; \
} \
+ (instancetype)shared##className { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); \
return instance; \
} \
- (id)copyWithZone:(NSZone *)zone { return instance; }
#else
// MRC 版本
#define singletonImplementation(className) \
+ (instancetype)allocWithZone:(struct _NSZone *)zone { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
if (instance == nil) { instance = [super allocWithZone:zone]; } \
}); \
return instance; \
} \
+ (instancetype)shared##className { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); \
return instance; \
} \
- (id)copyWithZone:(NSZone *)zone { return instance; } \
- (oneway void)release {} \
- (instancetype)retain { return instance; } \
- (instancetype)autorelease { return instance; } \
- (NSUInteger)retainCount { return ULONG_MAX; }
#endif
// 注意:巨集的最後一行「不要」留反斜線
另外提醒,巨集展開時會用到一個名為 instance 的靜態變數,記得在 .m 檔案的實作區塊頂端宣告 static id instance;。