1.前言
转载请注明出处
http://blog.csdn.net/wangguoyang429883793/article/details/50353996
大道至简,swift的单例应该是很简单的。
2.几种单例
1.最简单:
这种写法要求在swift 1.2 以上版本,1.2一下的class不支持static。
class Singleton {
static let sharedInstance = Singleton()
private init() {}
}
说明:
①就是私有化构造方法。private init() {}
②就是对外提供访问点。static let sharedInstance = Singleton() let保证不可更改。
③“全局变量(静态成员变量和结构体以及枚举)的延迟构造器在其被第一次访问时会加载,并以dispatch_once的方式启动来确保初始化的原子性。
2.较简单:
- 适用于1.2一下 class 不支持 static
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
}
3.较复杂:
- 由oc直接演变过来:
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!
}
}
3.总结
swift 1.2 推荐使用第一种啊。
参考地址http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift
欢迎批评,吐槽,点赞,留言。