zoukankan      html  css  js  c++  java
  • Swift中的单例的实现方式

      单例在iOS日常开发中是一个很常用的模式。对于希望在 app 的生命周期中只应该存在一个的对象,保证对象的唯一性的时候,一般都会使用单例来实现功能。在OC单例的写法如下:

    @implementation Singleton
    + (id)sharedInstance {
        static Singleton *staticInstance = nil;
    
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            staticInstance = [[self alloc] init];
        });
        return staticInstance;
    }
    @end
    

      那么在swift中,我们怎么写单例呢。首先,单例必须是唯一的,在一个应用程序的生命周期里,有且只有一个实例存在。为了保持一个单例的唯一性,单例的构造器必须是私有的。这防止其他对象也能创建出单例类的实例。为了确保单例在应用程序的整个生命周期是唯一的,它还必须是线程安全的。

      那么,根据OC的写法,改编一下成为Swift的单例应该这样写: 

    class Singleton {
        class var sharedInstance : Singleton {
            struct Static {
                static var onceToken : dispatch_once_t = 0
                static var instance : Singleton? = nil
            }
            
            dispatch_once(&Static.onceToken) {
                Static.instance = Singleton()
            }
            
            return Static.instance!
        }
    }

      这种写法当然没有错,但是Swift当然有更简洁的写法:

      结构体写法:

    class Singleton {
        class var sharedInstance: Singleton {
            struct Static {
                static let instance = Singleton()
            }
            return Static.instance
        }
    }
    

      这种写法是在Swift1.0版本的时候,必须的写法,因为Swift1.0,类还不支持全局类变量。而结构体却支持。

    还有其他的写法

    喵神推荐的写法是:

    private let sharedInstance = MyManager()
    class MyManager  {
        class var sharedManager : MyManager {
            return sharedInstance
        }
    }
    

    点击打开链接

    还有没有更简单的写法?有,下面一种:

    class Singleton {
        static let sharedInstance = Singleton()
        private init() {} // 阻止其他对象使用这个类的默认的'()'初始化方法
    }
    

     毕竟Swift2.0刚出来不久,没有像OC一样,基本上全世界的开发者都是一个写法,很多东西都要互相借鉴探讨。感谢共享知识的所有人,感谢Google。

    以上内容参考文章链接为:swifter.tips ,swift308 ,stackoverflow

     

      

  • 相关阅读:
    Python经典的算法题【多测师】
    百度流氓驱动bd0001.sys【多测师】
    github上的前端面试题
    利用H5 FormData 实现表单中多图上传(可带其他如String类型数据)
    border-color的深入理解
    一个好玩的小制作,以及在<a/>中的标签href="javascript:;"/href="javascript:void(0);"/href="javascript:"的用法
    css进行网站布局
    Mybatis中的<trim>标签应用
    css居中小技巧
    css布局模型
  • 原文地址:https://www.cnblogs.com/code-cd/p/4811685.html
Copyright © 2011-2022 走看看