Swift 中创建单例

2016-09-08  本文已影响18人  chenyu1520
class MyClass: NSObject {
    static let shareInstance = MyClass()
    private override init() {}
}

通过分析 stack trace 后发现,执行下面代码时,调用了 dispatch_once_f,然后又调用了 _dispatch_client_callout,由此说明这里是线程安全的。

static let shareInstance = MyClass()

使用私有的方式重写 init 方法,是为了避免其他类直接调用单例类的 init 方法获得新的对象。

上一篇 下一篇

猜你喜欢

热点阅读