swift 单利创建的几种方式

1 篇文章 0 订阅

swift 单利创建的几种方式

苹果官方推荐

In Swift, you can simply use a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:

class Singleton {
    static let sharedInstance = Singleton()
}
If you need to perform additional setup beyond initialization, you can assign the result of the invocation of a closure to the global constant:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}

非正式:

class SwiftSingleton {   
    class var shared: SwiftSingleton {   
    if !Inner.instance {   
        Inner.instance = SwiftSingleton()   
        }   
        return Inner.instance!   
    }   

    struct Inner {   
        static var instance: SwiftSingleton?   
    }   
}   

这段代码的实现,在shared中进行条件判断,如果Inner.instance.为空就生成一个实例,这段代码很简单看出当线程同时访问SwiftSingleton.shared方法时,会有如下问题出现,线程A判断Inner.instance为空,进入if语句后立即切换到线程B执行,线程B也进行判断,由于线程A只是进入了if语句,这行代码
Inner.instance = SwiftSingleton()

并没有执行,这时Inner.instance还是为空,纯种B也进行了if语句,这种情况下就会创建多个实例,没有保证实例的唯一性。

参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值