0% found this document useful (0 votes)
16 views

Automatic Reference Counting

Uploaded by

berkay.unal579
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Automatic Reference Counting

Uploaded by

berkay.unal579
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Automatic Reference Counting

Swift uses Automatic Reference Counting (ARC) to track and manage your app’s
memory usage. In most cases, this means that memory management “just works” in
Swift, and you don’t need to think about memory management yourself. ARC
automatically frees up the memory used by class instances when those instances
are no longer needed.

However, in a few cases ARC requires more information about the relationships
between parts of your code in order to manage memory for you. This chapter
describes those situations and shows how you enable ARC to manage all of your
app’s memory.

Reference counting applies only to instances of classes. Structures and


enumerations are value types, not reference types, and aren’t stored and passed by
reference.

How ARC Works

Every time you create a new instance of a class, ARC allocates a chunk of memory
to store information about that instance. This memory holds information about the
type of the instance, together with the values of any stored properties associated
with that instance.

Additionally, when an instance is no longer needed, ARC frees up the memory used
by that instance so that the memory can be used for other purposes instead. This
ensures that class instances don’t take up space in memory when they’re no longer
needed.

However, if ARC were to deallocate an instance that was still in use, it would no
longer be possible to access that instance’s properties, or call that instance’s
methods. Indeed, if you tried to access the instance, your app would most likely
crash.

To make sure that instances don’t disappear while they’re still needed, ARC tracks
how many properties, constants, and variables are currently referring to each class
instance. ARC will not deallocate an instance as long as at least one active
reference to that instance still exists.

To make this possible, whenever you assign a class instance to a property, constant,
or variable, that property, constant, or variable makes a strong reference to the
instance. The reference is called a “strong” reference because it keeps a firm hold on
that instance, and doesn’t allow it to be deallocated for as long as that strong
reference remains.

Keeping Track of the Retain Count

Every object in Swift – an instance of a class – has a property called retainCount.

When the retain count is greater than zero, the object is kept in memory
When this retain count reaches zero, the object is removed from memory
As we’ve discussed, only reference types, such as classes, have a retain count. A
value type, such as a struct, is copied when it’s passed around in your code; there’s
nothing to reference or retain. ARC only affects instances that are “shared” or
passed-by-reference in your code.

Before we move on, let’s look at an analogy. Imagine a scenario where 3 persons –
Berg, Pete and Sharon – share a piece of paper with a phone number written on it.
We’re calling that piece of paper with the phone number paper. The paper is an
instance of a Swift class, of course.

You can visualize this as 3 persons holding onto a piece of paper, grabbing it with
their hands. It could be the phone number of a pizza place, for example. Berg, Pete
and Sharon all need the phone number for something, so that’s why they’re holding
onto that one shared piece of paper.

At this point, the retain count of paper is 3. Why? Because 3 persons are holding
onto the paper object. This has a consequence: the paper object cannot be removed
from memory, because it’s still in use.

At some point, Sharon doesn’t hold onto the paper with the phone number anymore.
Pete also lets go of paper. They’re done calling the phone number, for example. The
retain count is reduced to 2, and then to 1. Only Berg is holding on to paper. The
data is not yet removed from memory.

Finally, Berg lets go of the piece of paper as well. You can imagine he just forgets he
had it… This reduces the retain count of paper to zero, which promptly removes the
paper object from memory. It’s not needed anymore, so the memory it used is freed
up for other apps.

Let’s discuss how this works in practical Swift programming.

Technically, when you create an object of a particular class type, that object is called
an instance, as in, “an instance of a class”. This is common terminology from Object-
Oriented Programming principles. In modern day programming, and going forward,
we often refer to “instances” as “objects”.
Resolving Strong Reference Cycles Between Class Instances

Swift provides two ways to resolve strong reference cycles when you work with
properties of class type: weak references and unowned references.

Weak and unowned references enable one instance in a reference cycle to refer to
the other instance without keeping a strong hold on it. The instances can then refer
to each other without creating a strong reference cycle.

Use a weak reference when the other instance has a shorter lifetime — that is, when
the other instance can be deallocated first. In the Apartment example above, it’s
appropriate for an apartment to be able to have no tenant at some point in its
lifetime, and so a weak reference is an appropriate way to break the reference cycle
in this case. In contrast, use an unowned reference when the other instance has the
same lifetime or a longer lifetime.

Common Problems with ARC

You see how keeping track of which object references others can get complicated.
It’s super helpful that this is an (almost) automatic mechanism, thanks to ARC.

In the previous section, we’ve briefly discussed strong references. They hold onto
instances that are referenced, by increasing their retain count. Strong references
have a counter-part: weak references. Weak references do not increase an
instance’s retain count.

Based on that, you can accidentally cause 2 common problems with ARC:

● A reference that’s weak when you need it to be strong, so the instance is


removed from memory when you still need it later on
● A reference that’s strong when you need it to be weak, and that causes a
retain cycle

Especially the retain cycle is a challenging problem. It’s quite simple: two objects
hold onto each other with strong references, which means neither of them can be
removed from memory because both their retain counts are greater than zero. This
creates a memory leak, which is what we wanted to avoid in the first place by doing
memory management and being a “good citizen”.

You can solve a retain cycle by designating either of the strong references as weak,
but you’ll have to account for that change in your code too of course. Retain cycles
also affect optionals, and for example [weak self] and unowned in closures. We’ll
leave that for another tutorial!
Resources

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/
automaticreferencecounting/

https://www.appypie.com/automatic-reference-counting-arc-swift

You might also like