- Swift 中使用单行单例法来创建单例,代码如下:
class MyClass: NSObject {
static let shareInstance = MyClass()
private override init() {}
}
通过分析 stack trace 后发现,执行下面代码时,调用了 dispatch_once_f,然后又调用了 _dispatch_client_callout,由此说明这里是线程安全的。
static let shareInstance = MyClass()
使用私有的方式重写 init 方法,是为了避免其他类直接调用单例类的 init 方法获得新的对象。
网友评论