I'm trying to explain ownership of objects and how GCD does its work. These are the things I've learned:
- a function will increase the retain count of the object its calling against
- a dispatch block, unless it captures
self
weakly will increase the count. - after a dispatched block is executed it release the captured object, hence the retain count of
self
should decrease. But that's not what I'm seeing here. Why is that?
class C {
var name = "Adam"
func foo () {
print("inside func before sync", CFGetRetainCount(self)) // 3
DispatchQueue.global().sync {
print("inside func inside sync", CFGetRetainCount(self)) // 4
}
sleep(2)
print("inside func after sync", CFGetRetainCount(self)) // 4 ?????? I thought this would go back to 3
}
}
Usage:
var c: C? = C()
print("before func call", CFGetRetainCount(c)) // 2
c?.foo()
print("after func call", CFGetRetainCount(c)) // 2