关于单例,有三个重要的准则需要牢记:
单例必须是唯一的,在程序生命周期中只能存在一个这样的实例。单例的存在使我们可以全局访问状态。
为保证单例的唯一性,单例类的初始化方法必须是私有的。这样就可以避免其他对象通过单例类创建额外的实例。
单例必须是线程安全的。如果有两个线程同时实例化一个单例对象,就可能会创建出两个单例对象。也就是说,必须保证单例的线程安全性,才可以保证其唯一性。通过调用dispatch_once,即可保证实例化代码只运行一次。
第一种:使用dispatch_once
class Singleton: NSObject {
class func shareInstancedispatch() -> Singleton {
struct Static {
static var predicate: dispatch_once_t = 0
static var instance: Singleton? = nil
}
dispatch_once(&Static.predicate) { () -> Void in
Static.instance = Singleton()
}
return Static.instance!
}
// override init() {
// super.init()
// }
private override init() {
super.init()
//do something when initialed
}
}
第二种:使用static let
//This approach supports lazy initialization because Swift lazily initializes class constants (and variables),and is thread safe by the deFinition of let.
class Singleton: NSObject {
static let sharedInstance = Singleton()
private override init() {
super.init()
//do something when initialed
}
}
原文地址:https://www.jb51.cc/swift/324314.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。