0

Swift Code

 override func viewDidLoad() {
            super.viewDidLoad()
            var v1 = ViewController()
            let v2 = ViewController2()
            print("\(CFGetRetainCount(v1)) and \(CFGetRetainCount(v2))")
        }

In Swift reference count printing as 2 and 2

Objective C Code

- (void)viewDidLoad {
    [super viewDidLoad];
    ViewController *v1 = [[ViewController alloc]init];
    ViewController2 *v2 = [[ViewController2 alloc]init];
    NSLog(@"%ld and %ld",CFGetRetainCount((__bridge CFTypeRef)(v1)),CFGetRetainCount((__bridge CFTypeRef)(v2)));
} 

In Objective C reference count printing as 1 and 1

Why reference counts are different in objective c and swift ?

Hari R Krishna
  • 782
  • 6
  • 20
  • 1
    Swift will pass the arguments as owned (+1) parameters, so will retain them before calling `CFRetainCount` (though this could be eliminated with ARC optimisation as `v1` and `v2` aren’t used after the function call). Though Swift is soon to use guaranteed (+0) parameters as the default convention. Your Obj-C code just does bridging casts that don’t transfer ownership, so no additional retains. But why is this important? You should never ever rely on value of `CFRetainCount`. – Hamish Mar 14 '18 at 13:29
  • So is there any way to print the exact retain count in swift? – Hari R Krishna Mar 14 '18 at 13:35
  • Technically it *is* printing the exact retain count ;) The thing is that you cannot rely on that value; Swift is free to insert and remove retain and release calls as it sees fit (and that’s not even considering things like tagged pointers). What are you trying to achieve here? – Hamish Mar 14 '18 at 13:47
  • 2
    Related: https://stackoverflow.com/questions/4636146/when-to-use-retaincount, http://www.friday.com/bbum/2011/12/18/retaincount-is-useless/, http://sdarlington.github.io – Martin R Mar 14 '18 at 14:10

1 Answers1

7

It has never been the case that you could rely on the retain count having a particular absolute value. Even in the days before ARC in Objective-C, you could not attribute any real significance to the retain count. All you cared about is that you matched the number of retains and releases that you wrote and if you retained the object more than you have released it, you owned it and it will therefore not go away.

If you have a problem with an object disappearing before it should do or one not going away when it should, you should use the object allocation profiling tools to find the problem, not print out the retain count. The retain count is just an implementation detail. It might even go away altogether in the future.

In both of the above two cases, Swift and Objective-C are doing things behind the scenes that you don't know about or should care about. Both numbers are right in the context.

JeremyP
  • 84,577
  • 15
  • 123
  • 161