單例模式的意思很直白:整個程式執行期間只存在一個實例,由類別自己負責建立,並向全系統提供這個唯一的入口。它常用來包裝需要全域共享的物件,例如網路連線、資料庫、設定管理或日誌。
先在標頭檔中宣告一個類別方法:
#import <Foundation/Foundation.h> @interface SingletonClass : NSObject + (id)sharedInstance; @end
#import "SingletonClass.h"
@implementation SingletonClass
static SingletonClass *getInstance;
+ (id)sharedInstance {
@synchronized ([SingletonClass class]) {
if (getInstance == nil) {
getInstance = [[SingletonClass alloc] init];
}
}
return getInstance;
}
@end
這裡用 @synchronized 把建立動作用同一把鎖包住,避免多執行緒同時呼叫時重複配置出兩個物件。這一步在多執行緒環境下是必要的,少了它單例就不再是單例。
[[SingletonClass sharedInstance] xxx];
取得物件後就能直接呼叫它的方法或存取屬性,不需要自己持有引用。
單例的釋放通常安排在應用程式即將結束時,於 App Delegate 中觸發:
- (void)applicationWillTerminate:(UIApplication *)application
{
[SingletonClass destroyDealloc];
}
對應的類別方法:
+ (void)destroyDealloc
{
if ([getInstance retainCount] != 1)
return;
[getInstance release];
getInstance = nil;
}
這裡先檢查 retainCount 是否為 1,是為了確認沒有其他地方還持有這個物件,避免提早釋放造成後續崩潰。
好處:
缺點:
補充一點:如果你使用 Swift 或較新的 Objective-C(ARC 環境),標準寫法會更簡潔,例如 Objective-C 用 + (instancetype)sharedInstance 搭配 dispatch_once,就不需要自行處理 retainCount 與 release 的細節。