Search code examples
iosobjective-cswiftreference-countingretaincount

Object reference count is different in swift and objective c


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 ?


Solution

  • 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.