單例模式就是只有一個實例,確保一個類只有一個實例,並且自行實例化並向整個系統提供這個實例,一個單例類可以實現在不同的窗口之間傳遞數據。
在oc中要實現一個單例類,至少需要做以下四個步驟:
1、為單例對象實現一個靜態實例,並初始化,然後設置成nil,
2、實現一個實例構造方法檢查上面聲明的靜態實例是否為nil,如果是則新建並返回一個本類的實例,
3、重寫allocWithZone方法,用來保證其他人直接使用alloc和init試圖獲得一個新實力的時候不產生一個新實例,
4、適當實現allocWitheZone,copyWithZone,release和autorelease
+(instancetype)shareAccount;
static CZAccount *account = nil;
+(instancetype)shareAccount{
if (!account) {
account = [[self alloc] init];
}
return account;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
account = [super allocWithZone:zone];
});
return account;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//MethodLog
warning 登錄賬號數據初始化在allocWithZone方法
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;
}