I'm experimenting the retain cycle in closure like following
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)
}
}
}
Later at some point, I'm doing
var sample : Sample? = Sample()
sample?.closure()
dispatch_async(dispatch_get_global_queue(0, 0)) {
usleep(100)
sample = nil
}
The output will be
Addition is 6
Destroying Sample
This is understandable because self
is nil out before doing self?.additionOf(3, b:5)
If I made a change inside the closure by creating another variable which references to [weak self]
like following
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)
}
This time, the output is
Addition is 6
Addition is 8
Destroying C
My question is why strongSelf
is not nil out after sample = nil
. Is it because it is captured inside the closure before sample = nil