GCD in Swfit 3.0
主要是嘚瑟一下英文。其实代码都在,什么文都无所谓。代码在这里:https://github.com/future-challenger/Swift3.0/tree/master/GCD This project is “forked” from raywenderlich GCD tutorial. It’s really a good tutorial where I learned what I wanted. But it’s kinda out of date. In Swift 3.0,lots of API in iOS SDK have been modified. Including how GCD APIs are called. So I update the tutorial to swift 3.0 Main Queue
Global Queue
dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.value),0)
Swift 3.0 DispatchQueue.global(qos: .userInteractive)
Here’s a easy one. Before we always do things like this: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^{
// do something background
dispatch_async(dispatch_get_main_queue(),^{
// update UI in main thread(or UI thread)
});
});
In swift 3.0,we do it this way. DispatchQueue.global(qos: .userInitiated).async {
// background things
DispatchQueue.main.async {
print("main thread dispatch")
}
}
Dispatch After & OnceDispatch Afterbefore you do dispatch after like this: var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW,Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime,dispatch_get_main_queue(),{
// your function here
})
In swift 3.0 let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime,execute: {
// your function here
})
or even more simply: DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Disaptch OnceThis According to Apple’s migration guide: The free function dispatch_once is no longer available in Swift. In Swift,you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided.
You can use lazy initialized global or static properties instead of dispatch once. eg: // 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")
}
}
reference: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |