美文网首页
ios 单例 Singleton

ios 单例 Singleton

作者: mayday2024 | 来源:发表于2015-05-17 17:15 被阅读131次

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

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

}

相关文章

  • iOS单例

    iOS 单例[https://www.cnblogs.com/dins/p/ios-singleton.html]...

  • 单例模式 Singleton Pattern

    单例模式-菜鸟教程 iOS中的设计模式——单例(Singleton) iOS-单例模式写一次就够了 如何正确地写出...

  • 单例模式(Singleton)

    单例模式(Singleton) 枚举单例 public enum Singleton { INSTANCE; ...

  • ios 单例 Singleton

    单例模式就是只有一个实例,确保一个类只有一个实例,并且自行实例化并向整个系统提供这个实例,一个单例类可以实现在不同...

  • iOS单例_Singleton

    单例的案例 单例是什么: 保证某个类创建出来的对象永远只有1个; 节省内存开销 保证数据或者资源的一致性 单例...

  • IOS SingleTon单例

    做移动端开发已经将近一年了,这是我第一次写博客,这是我第一将感想和大家分享,写的不是很好希望大家多多包涵 单例模式...

  • iOS知识点总结(1)

    1. iOS单例的实现方式? 之前总是这样写: static Singleton *shareSingleton ...

  • 单例对象

    iOS单例模式(Singleton)单例模式的意思就是:只有一个实例;单例模式确保每个类只有一个实例,而且自行实例...

  • 设计模式(2) 单例模式

    单例模式 线程安全的Singleton 会破坏Singleton的情况 线程级Singleton 单例模式是几个创...

  • 单例模式

    3、单例模式(Singleton) 单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象...

网友评论

      本文标题:ios 单例 Singleton

      本文链接:https://www.haomeiwen.com/subject/ggakqttx.html