• 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

     

      

  • 相关阅读:
    洛谷P2124 奶牛美容
    UVA10325 The Lottery
    CF979C Kuro and Walking Route
    洛谷P4318 完全平方数(莫比乌斯函数)
    hdu2204 Eddy's爱好(莫比乌斯函数)
    LOJ#6053. 简单的函数(min_25筛)
    洛谷P5325 【模板】Min_25筛
    超级码力在线编程大赛初赛 第3场 2.房屋染色
    超级码力在线编程大赛初赛 第3场 3.字符串游戏(Anti-Nim)
    超级码力在线编程大赛初赛 第3场 1.最大公倍数
  • 原文地址:https://www.cnblogs.com/code-cd/p/4811685.html
Copyright © 2020-2023  润新知