Swift3中dispatch_once废弃的解决办法

在Swift中如果想搞类的单例模式,那么在初始化的时候一般会使用just one time执行的方式,我们使用dispatch_once_t配合调用dispatch_once方法,一般的代码如下

staticvar token: dispatch_once_t = 0

func whatDoYouHear() {    

print("All of this has happened before, and all of it will happen again.")  

dispatch_once(&token) {  

print("Except this part.") }

}

不过在Swift3中会提示此法行不通,dispatch_xxx已废弃,use lazily initialized globals instead.

原来自从swift 1.x开始swift就已经开始用dispatch_one机制在后台支持线程安全的全局lazy初始化和静态属性.所以static var背后已经在使用dispatch_once了.网友的解释是:

Sothe static var above was already using dispatch_once, which makes it sort of weird (and possibly problematic to use it again as a token for another dispatch_once. In fact there's really no safe way to use dispatch_once without this kind of recursion, so they got rid ofit. Instead, just use the language features built onit

所以现在的swift3中干脆把dispatch_once显式的取消了.

我们再Swift3中若要想实现原来dispatch_once的机制可以用以下几种办法:

1.使用全局常量

let foo = SomeClass()

2.带立即执行闭包初始化器的全局变量:

var bar: SomeClass = {  

let b = SomeClass()  

b.someProperty ="whatever"  

b.doSomeStuff()  

return b}()

3.类,结构,枚举中的静态属性:

class MyClass {
    static let singleton = MyClass()
    init() {
        print("foo")
    }
}

你还可以直接创建一个全局的变量或静态属性来达到没有结果的just one time:

classMyClass {  

static let singleton = MyClass()  

init() {  

print("foo") }

}

如果你觉得这都不和你的胃口,你可以在需要调用justAOneTimeThing的地方直接调用它就是啦:

func doTheOneTimeThing()

justAOneTimeThing

}

所以在Swift3中推荐使用如下方法来完成一个单例:

  1. final class Single: NSObject {  
  2.     static let shared = Single()  
  3.     private override init() {}  
  4. }

final关键字的作用是这个类或方法不希望被继承和重写

以上就是Swift3中dispatch_once废弃的解决办法的全文介绍,希望对您学习和使用swift编程开发有所帮助.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值