
如何用swift写GCD
1个回答
展开全部
一般只需要这样写就可以
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//需要长时间处理的代码
dispatch_async(dispatch_get_main_queue(), {
//需要主线程执行的代码
})
})
如果运行一系列的任务,希望当任务全部结束后运行另一个特殊的任务这种场景就是用下面的写法
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let group = dispatch_group_create()
for(id obj in array)
dispatch_group_async(group, queue, {
self.doWork(obj)
})
dispatch_group_notify(group, queue, {
self.doneWork
})
dispatch_release(group)
如果嫌swift还不够简洁也可以使用duemunk写的GCD语法糖Async,项目github地址:https://github.com/duemunk/Async
语法看起来是这样
Async.background {
println("This is run on the background queue")
}.main {
println("This is run on the main queue, after the previous block")
}
支持的方法
Async.main {}
Async.userInteractive {}
Async.userInitiated {}
Async.default_ {}
Async.utility {}
Async.background {}
多少个blocks的chain都可以
Async.userInitiated {
// 1
}.main {
// 2
}.background {
// 3
}.main {
// 4
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//需要长时间处理的代码
dispatch_async(dispatch_get_main_queue(), {
//需要主线程执行的代码
})
})
如果运行一系列的任务,希望当任务全部结束后运行另一个特殊的任务这种场景就是用下面的写法
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let group = dispatch_group_create()
for(id obj in array)
dispatch_group_async(group, queue, {
self.doWork(obj)
})
dispatch_group_notify(group, queue, {
self.doneWork
})
dispatch_release(group)
如果嫌swift还不够简洁也可以使用duemunk写的GCD语法糖Async,项目github地址:https://github.com/duemunk/Async
语法看起来是这样
Async.background {
println("This is run on the background queue")
}.main {
println("This is run on the main queue, after the previous block")
}
支持的方法
Async.main {}
Async.userInteractive {}
Async.userInitiated {}
Async.default_ {}
Async.utility {}
Async.background {}
多少个blocks的chain都可以
Async.userInitiated {
// 1
}.main {
// 2
}.background {
// 3
}.main {
// 4
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询