0

You can put the following code snippet into the Xcode playground

import CoreFoundation

class MyData {
    let someInt = 1
}
let a = MyData() //Definition of the varialbe a
print(CFGetRetainCount(a)) // it prints out 2
} 

The only thing the code does is initialize an object of type MyData and assign it to a constant named a

I thought it would be only 1 reference (the constant a) "points to" the object, however, it turns out the object already has 2 references "point to" it.

Question:

  1. Who is this second reference?

  2. If the constant a is deallocated/destroyed then the object will not be deallocated because there is still a reference "points to" the object. (I guess my understanding is wrong, please point out any errors)

Thanks

SLN
  • 4,772
  • 2
  • 38
  • 79
  • It doesn't reproduce if you compile this code to an executable using `swiftc`, so it's most likely a playgrounds artifact. – zneak Aug 16 '17 at 17:55
  • 3
    Querying the retain count is almost always pointless: https://stackoverflow.com/questions/4636146/when-to-use-retaincount, http://sdarlington.github.io. – Martin R Aug 16 '17 at 18:01
  • @MartinR Thx, good to know that – SLN Aug 16 '17 at 18:02
  • 1
    Looks like `a` gets passed as a guaranteed parameter, so caller retains the `MyData` instance before the call to `CFGetRetainCount` and releases after, hence why the retain count is reported as 2. In an optimised build, the compiler can eliminate that retain/release overhead (as it knows the instance is already +1 retained), therefore the retain count is reported as 1. And this is a perfect illustration of how, as Martin says, the querying the retain count of an instance is pointless :) – Hamish Aug 16 '17 at 21:57

0 Answers0