ios 单例 Singleton

2015-05-17  本文已影响131人  mayday2024

单例模式就是只有一个实例,确保一个类只有一个实例,并且自行实例化并向整个系统提供这个实例,一个单例类可以实现在不同的窗口之间传递数据。

在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;

}

上一篇 下一篇

猜你喜欢

热点阅读