前端之家收集整理的这篇文章主要介绍了
在swift 3中的dispatch_once?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
301_0@
好吧,所以我发现了新的
Swifty Dispatch API在Xcode 8。我有乐趣使用DispatchQueue.main.async,我已经浏览了Xcode中的Dispatch模块,以找到所有新的API。
但是我还使用dispatch_once来确保单例创建和一次性设置等事情不会被执行多次(即使在多线程环境中)…和dispatch_once在新的Dispatch模块中是无处不在的吗?
static var 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.")
}
}
从Swift 1.x开始,Swift已经使用dispatch_once
behind the scenes来执行
全局变量和静态
属性的线程安全延迟初始化。
所以上面的静态var已经使用了dispatch_once,这使得它奇怪(可能有问题再次使用它作为另一个dispatch_once的令牌。事实上,没有这种递归,没有安全的方式使用dispatch_once,所以他们得到相反,只是使用基于它的语言功能:
// global constant: SomeClass initializer gets called lazily,only on first use
let foo = SomeClass()
// global var,same thing happens here
// even though the "initializer" is an immediately invoked closure
var bar: SomeClass = {
let b = SomeClass()
b.someProperty = "whatever"
b.doSomeStuff()
return b
}()
// ditto for static properties in classes/structures/enums
class MyClass {
static let singleton = MyClass()
init() {
print("foo")
}
}
所以这很棒,如果你一直使用dispatch_once一次性初始化,导致一些价值 – 你可以使该值的全局变量或静态属性你正在初始化。
但是如果你使用dispatch_once来做不一定有结果的工作呢?你仍然可以使用全局变量或静态属性:只是使该变量的类型Void:
let justAOneTimeThing: () = {
print("Not coming back here.")
}()
如果访问一个全局变量或静态属性来执行一次性工作,就不会感觉到你 – 例如,你希望客户端在使用你的库之前调用“初始化我”函数 – 只是换行在函数中访问:
func doTheOneTimeThing() {
justAOneTimeThing
}
更多信息参见migration guide。