jignesh Vadadoriya jignesh Vadadoriya - 12 days ago 6
Swift Question

Reference count in ARC

i have little bit confusion in ARC reference count can you please tell me what will be reference count of bellow code.

var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3



  1. what will be the reference count of vc1?

  2. what will be the reference count of vc2?

  3. what will be the reference count of vc3?

  4. what will be the reference count of vc4?


Answer

Here, vc1, vc2, vc3 refer to the same object. So, the reference count of that object is 3. When vc4 refer to the same object, since it is weak reference, the reference count will not be incremented by 1. So, the reference count after this will also be 3

  1. The reference count of UIViewController object that is created and referred by vc1 after first line of code is 1.

    var vc1:UIViewController = UIViewController() 
    
  2. After vc2 refers to the same object as vc1. The reference count of object turns to 2

    var vc2:UIViewController = vc1
    
  3. After vc3 refers to the same object as vc1 and vc2. The reference count of object turns to 3

    var vc3:UIViewController = vc2
    
  4. After vc4 refers to the same object as vc1, vc2 and vc3. Since vc4 is weak reference, the reference count will not be incremented. That means the count is still 3.

    weak var vc4:UIViewController? = vc3
    

What it means:

Execute the following code.

   vc1 = nil; // reference count = 3-1 = 2
   vc2 = nil; // reference count = 2-1 = 1
   vc3 = nil; // reference count = 1-1 = 0 and object is destroyed

Now, print the value of vc4. It will be nil. This happens because the reference count of object turns to zero and all of the variables refers to same object.