我正在尝试关闭保留周期,如下所示
class Sample {
deinit {
print("Destroying Sample")
}
func additionOf(a: Int, b:Int) {
print("Addition is \(a + b)")
}
func closure() {
dispatch_async(dispatch_get_global_queue(0, 0)) { [weak self] in
self?.additionOf(3, b: 3)
usleep(500)
self?.additionOf(3, b: 5)
}
}
}
稍后在某个时候,我正在做
var sample : Sample? = Sample()
sample?.closure()
dispatch_async(dispatch_get_global_queue(0, 0)) {
usleep(100)
sample = nil
}
输出将是
Addition is 6
Destroying Sample
这是可以理解的,因为self
在做之前是 nil outself?.additionOf(3, b:5)
如果我通过创建另一个引用[weak self]
如下变量的变量在闭包内进行了更改
dispatch_async(dispatch_get_global_queue(0, 0)) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.additionOf(3, b: 3)
usleep(500)
strongSelf.additionOf(3, b: 5)
}
这次的输出是
Addition is 6
Addition is 8
Destroying C
我的问题是为什么strongSelf
在sample = nil
. 是不是因为之前在闭包里面被捕获了sample = nil