iOS开发之Weak Singleton

导读

iOS weak 关键字漫谈
Objective C & iOS Weak Singletons

从以上导读中我见识到了weak的新用法或者说新的应用场景:单例。

我们之前的做法都是用一个static来修饰的强指针来持有这个单例,那这样的话这个单例就会跟随程序的生命周期知道进程杀死。那有时候这个单例可能依托于某一个视图控制器或者某一个功能模块,只要这个视图控制器或者功能模块销毁了那这个单例对象也就毫无意义了,那这个时候如果采用全局单例就会有内存浪费,所以有了今天的Weak Singleton。

那么从导读上的文章我说一下步骤代码:

代码如下

1、构建单例

//采用锁的方式构建
+ (instancetype)sharedInstance
{
    //static修饰的是弱引用指针
    static __weak ASingletonClass *instance;
    ASingletonClass *strongInstance = instance;
    @synchronized(self) {
        if (strongInstance == nil) {
            strongInstance = [[[self class] alloc] init];
            instance = strongInstance;
        }
    }
    return strongInstance;
}
//采用锁的方式构建
+ (instancetype)sharedInstance
{
    //static修饰的是弱引用指针
    static __weak ASingletonClass *instance;
    ASingletonClass *strongInstance = instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
         if (strongInstance == nil) {
            strongInstance = [[[self class] alloc] init];
            instance = strongInstance;
    });
    return strongInstance;
}

2、作为某一个类的实例变量或者属性也是可以的,但是属性得是强引用

//实例变量
{
    ASingletonClass *_singletonInstance;
}
//属性
@property (nonatomic, strong) ASingletonClass * singletonInstance;

3、创建这个单例对象,并赋值给实例变量

_singletonInstance = [ASingletonClass sharedInstance];

PS: 其中ASingletonClass指的是单例类

但是呢这个单例类必须得被别的类强引用要不然创建之后就会释放,其实和之前的普通的本类全局的强引用是一样的,只不过起到了在本类没释放掉之前都是同一个对象的效果。

以上!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,378评论 30 472
  • 把网上的一些结合自己面试时遇到的面试题总结了一下,以后有新的还会再加进来。 1. OC 的理解与特性 OC 作为一...
    AlaricMurray阅读 7,378评论 0 20
  • 1.属性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作...
    曾令伟阅读 4,695评论 0 10
  • 原文 序言 目 前形势,参加到iOS队伍的人是越来越多,甚至已经到供过于求了。今年,找过工作人可能会更深刻地体会到...
    星空下的菜地阅读 8,215评论 3 42
  • CP:绝望x懒惰。 梗:原著衍生。 注意事项:自带避雷针护目镜以免受到伤害。 —————————— 组织对于失败...
    祺墨夏阅读 4,316评论 0 0