在OC中我们经常这样写单例:
@implemention MyManager
+ (id)sharedManager {
static MyManager *shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceTokec, ^{
shareInstance = [[self alloc] init];
});
return shareInstance;
}
使用dispatch_once_t来保证单例代码在生命周期内只被调用一次。
然而在Swift中,如下方式是最佳的单例实现方式:
private let sharedInstance = MyManager()
为什么简单的一个全局变量就可行呢?如何保证只调用了一次没有冲突呢?
The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.
Swift中的全局变量在初始化的时候都会使用 dispatch_once来保证原子性。所以Swift天生支持单例模式,简单方便。
网友评论