單例(Singleton)要求一個類別在整個應用生命週期中只存在一個實例,並提供全域的存取點。常見用途包含網路管理器、資料庫連線、使用者狀態、設定檔讀寫等——凡是「全 App 共用同一份狀態」的東西,都適合做成單例。
這是在 MRC(手動記憶體管理)時代最容易被忽略的細節。單例的生命週期應該等同應用程式本身,任何人都不該有機會把它釋放掉。因此 retain、release、autorelease、retainCount 這四個方法都要重寫成「什麼都不做」或「永遠回傳自己」,避免外部誤用造成引用計數歸零而被回收。
頭檔宣告
@interface SingletonTeather : NSObject @property (nonatomic, strong) NSString *name; @property (nonatomic, strong) NSMutableDictionary *info; + (SingletonTeather *)getSingletonTeather; @end
實作檔
static SingletonTeather *shareSingletonTeather = nil;
@implementation SingletonTeather
@synthesize name, info;
+ (SingletonTeather *)getSingletonTeather {
if (shareSingletonTeather == nil) {
shareSingletonTeather = [[SingletonTeather alloc] init];
}
return shareSingletonTeather;
}
// 攔截配置行為,確保 alloc 也只會產生同一個物件
+ (id)allocWithZone:(struct _NSZone *)zone {
if (shareSingletonTeather == nil) {
shareSingletonTeather = [super allocWithZone:zone];
}
return shareSingletonTeather;
}
- (id)copyWithZone:(struct _NSZone *)zone {
return self;
}
- (NSUInteger)retainCount {
return NSIntegerMax;
}
- (id)retain {
return self;
}
- (oneway void)release {
}
- (id)autorelease {
return self;
}
@end
只改 getSingletonTeather 是不夠的。使用者若直接寫 [[SingletonTeather alloc] init],就會繞過你的檢查而配置出第二個物件。把 allocWithZone: 一起攔下來,等於從源頭堵住了破口,這才是完整的單例寫法。
在 ARC 與 dispatch_once 普及之後,上述寫法可以簡化成極短的版本,由 GCD 保證執行緒安全與唯一性:
+ (instancetype)sharedInstance {
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
這也是目前 Apple 系統框架內部普遍採用的模式,比手寫記憶體方法更簡潔也更可靠。