深入理解GCD:从基础到应用优化
1. GCD与闭包基础
GCD(Grand Central Dispatch)使用闭包来封装要添加到队列的代码。在Swift中,闭包是一等公民,你可以将闭包赋值给变量、传递给方法,或者作为方法调用的结果返回。闭包类似于Objective - C的块,在其他编程语言(如Python)中有时也被称为lambda。和方法或函数类似,闭包可以接受一个或多个参数并指定返回值,但与GCD一起使用的闭包既不能接受参数也不能返回值。
以下是一个声明和执行闭包的示例:
// Declare a closure variable "loggerClosure" with no parameters
// and no return value.
let loggerClosure = {
print("I'm just glad they didn't call it a lambda")
}
// Execute the closure, producing some output in the console.
loggerClosure()
2. 优化SlowWorker的doWork方法
为了了解如何将闭包与GCD结合使用,我们来看一下 SlowWorker
的 doWork()
方法。原始的 doWork()
方法如下:
@IBAction func doWor