ARC

chandrakant kaski
Sep 7, 2018 · 3 min read

AUTOMATIC REFERENCES COUNTING

In order to understand the ARC, you need to know about basic things.
First, I would like to get you through those basics.

Instances of structures and enumerations are passed by value

Here we stored string1 in the variable str1. We then assigned the value of str1 to str2 Under the hood, the value of str1 is copied and stored in str2. This means that separate values are stored in str1 and str2. The values are equal, but, in memory, they are different. That’s what it means to pass by value. When the value of str1 was assigned to str2, it was passed by value.

Instances of classes are passed by reference

When we assigned person1 to person2, the value stored in person1 was not copied. Instead, the reference of the Person instance stored in person1 was assigned to person2. This means that person1 and person2 are pointing to the same Person instance. Only one instance of the Person class is present in memory.

Strong ref (ARC counts the reference)

Strong references should be used when a parent object is referencing a child object and never the other way around. That is, a child class should not have a strong reference to the parent class.

Weak and Unowned ref(ARC do not count the reference)

Unowned(value is mandatory): — will always have value but that will not be owned by self

Weak(value is optional):- will have value only if someone else will have a strong reference to the value

Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.

A weak reference can never be a constant because it needs to be able to mutate

ARC

The idea underlying ARC is simple. It keeps track of class instances and it decides when it’s safe to deallocate the class instances it monitors. It does this by counting the references for each class instance.

In the first image, we have created the two instances of the person so the reference count over there was 2.

Whereas in a second we made the person1 as nil so reference count decrements and becomes 1 but because of this 1 Person class is still alive i.e in memory.

If we make the person2 also nil the ARC will free up the space taken by the instance of the person so the instance will no longer available.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade