單例模式是在iOS開發中最常用的一種設計模式,單例模式可以讓程序的各個模塊共享數據,而不用去手動的去傳遞。所以單例類是一個我們要去理解的非常重要的模式,這種模式貫穿於iPhoneSDK中,例如UIApplication有一個方法叫做shareApplication用來共享當前程序的UIApplication實例。
添加一個ShareData類,在ShareData.h中聲明如下:
#import在ShareData.m中實現該類:@interface ShareData : NSObject { NSString *string; } @property (nonatomic, retain) NSString *string; + (id)sharedData; @end
#import "ShareData.h" @implementation ShareData @synthesize someProperty; #pragma mark Singleton Methods + (id)sharedData { static ShareData *sharedData = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedData = [[self alloc] init]; }); return sharedData; } - (id)init { if (self = [super init]) { self.string = [[[NSString alloc] initWithString:@"123"] autorelease]; } return self; } - (void)dealloc { self.string = nil; [super dealloc]; }
定義了一個在translation unit內全局唯一的靜態變量shareData,通過調用靜態方法shareData來初始化和獲取變量。通過調用Grand Central Dispatch(GCD)的dispatch_once方法來保證靜態變量只初始化一次,並且dispatch_once是系統保證的線程安全的。
在不用GCD的情況shareData方法的寫法如下:
+ (id)sharedData { static ShareData *sharedData = nil; @synchronized(self) { if (sharedData == nil) { sharedMyManager = [[self alloc] init]; } } return sharedData; }單例模式的使用如下:
ShareData *shareData = [ShareData sharedData];在非ARC(Automatic Reference Counting)下的實現代碼如下:
#import "ShareData.h" static ShareData *shareData = nil; @implementation ShareData @synthesize string; #pragma mark Singleton Methods + (id)shareData { @synchronized(self) { if(shareData == nil) { shareData = [[super allocWithZone:NULL] init]; } } return shareData; } + (id)allocWithZone:(NSZone *)zone { return [[self shareData] retain]; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (unsigned)retainCount { return UINT_MAX; //denotes an object that cannot be released } - (oneway void)release { // never release } - (id)autorelease { return self; } - (id)init { if (self = [super init]) { string = [[NSString alloc] initWithString:@"123"]; } return self; } - (void)dealloc { [string release]; [super dealloc]; } @end