單例模式的核心承諾是:一個類別在整個應用生命週期裡只有一個實例,由類別自己負責建立並對外提供。這樣做的好處很實際——不同的視圖控制器之間可以透過同一個物件傳遞狀態,不必到處傳參數。
在 Objective-C 裡寫一個單例,至少要完成下面四件事。
用一個類別層級的靜態變數保存實例,初始值設為 nil。
在這個方法裡檢查靜態實例是否為 nil,是則建立,然後回傳。
static CZAccount *account = nil;
+ (instancetype)shareAccount {
if (!account) {
account = [[self alloc] init];
}
return account;
}
光有 shareAccount 並不足以稱為單例,因為外部還是可以 alloc。用 dispatch_once 把 allocWithZone: 鎖住,能保證無論從哪個入口進來,拿到的記憶體位址都是同一塊。
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
account = [super allocWithZone:zone];
// 登入帳號資料初始化放在這裡
});
return account;
}
copyWithZone:、release、autorelease、retain 這些方法都可以覆寫成回傳 self,讓複製與引用計數操作都拿不到新物件。在 ARC 之下 retain/release 不需要處理,但 copyWithZone: 仍然值得覆寫。
一個實務上的選擇是把持久化資料的讀取寫在 allocWithZone: 裡,這樣無論走哪個入口,物件一誕生就帶著正確狀態:
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
account = [super allocWithZone:zone];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
account.access_token = [defaults objectForKey:@"access_token"];
account.remind_in = [defaults objectForKey:@"remind_in"];
account.expires_in = [defaults objectForKey:@"expires_in"];
account.uid = [defaults objectForKey:@"uid"];
});
return account;
}
不過這種寫法有個缺點值得注意:allocWithZone: 的職責被混入了業務邏輯,單元測試時不好替換資料來源。如果團隊講究職責分離,比較好的做法是在 allocWithZone: 裡只負責保證唯一性,把資料載入移到 shareAccount 或一個明確命名的 load 方法裡,並用 dispatch_once 各自保護。
另外提醒兩點:NSUserDefaults 不適合存放 token 這類敏感資訊,應該改用 Keychain;單例的生命週期等同 App 生命週期,因此不要在裡面積累無限成長的陣列或快取而沒有淘汰策略。