I came across CFGetRetainCount
while seeking for a way to log out how many references I've got on my iOS program at a moment in time.
As far as I could see, it shares the retain count for a given instance, which looks pretty much what I needed.
In fact, while playing with it in a blank Swift Playground, I could see the results change when I point a new reference for the instance I've created.
The odd part is - it is always starting at 2. Even for new instances. Why does it happen? Shouldn't it start at 1?
Here's my implementation:
import CoreFoundation
class John: NSObject {
deinit {
print("This john is gone")
}
}
var lilJohn: John? = John()
var bigJohn: John? = John()
CFGetRetainCount(lilJohn) // prints 2
CFGetRetainCount(bigJohn) // prints 2
// I've thought the "2" was because CFGetRetainCount was strongly capturing the argument when inputed, but...
weak var _lilJohn = lilJohn
weak var _bigJohn = bigJohn
CFGetRetainCount(_lilJohn) // still printing 2
CFGetRetainCount(_bigJohn) // same as above
Disclaimer: I'm aware that CFGetRetainCount
should only be used for debugging matters. I'm not using such function in a distributed app. This is not going live at all.
I also know CFGetRetainCount
results can't be trusted, as it doesn't share when/where the retain/release are being placed. I've found also the isKnownUniquelyReferenced
API, but what I'm really after is a count of references, not a boolean.