#SwiftyInfo — What in the world is ARC? — Part 1

Swift uses an internal in-app currency call Automatic Reference Counting. Yes the fact that its Automatic means much of the reference counting (memory) handling is already done for you by the system, but as an iOS developer, it is very important to understand how we manage memory in iOS so as to build a more efficient and robust app.

Say we have a very typical Person class, where we just initialised and created 3 instances of it.

Every time a new variable (person1, person2, person3) is written in code to reference (=) a new instance, the os will allocate a memory (coin) to the instance. This allows the app to continue to use values (i.e. name) by just calling out the variable name. As long as there is one reference (coin) given, the instance will be kept alive till it ran out of references.

So here we have another scenario where the os allocated three memory coins to one instance of “John”. This is also what we call STRONG reference. As long as the instance still has coins in hand, he will live. This is also where we finally understand why Apple calls this as automatic reference counting, every new reference increment the count automatically.
So how to kill “John”?
You might have notice that we are creating an optional reference for person1, if you need to understand more about optionals, do refer here. In a nutshell, to remove a coin from an instance to free up your bank account, you need to have optionals in your references. So once all the references are removed, memory is free up!

ARC is one of the most important concepts in iOS development when we talk about memory management. As the project scales, more references will be going around from classes to sub-classes etc where we have to pay attention to every single small details about such referencing pattern. In my next Part, I will be talking about Reference cycles which will normally lead to memory leaks, where the scenario of strong references happen between classes but are actually not needed in our app. Such scenarios will bloat up our app’s memory and cause many negative effects.
Before you go…
If you enjoyed this post, you will love Lawrey Swifty Weekly. It’s my FREE weekly digest of the best iOS-related nuggests and stuffs about life, productivity and self improvement. Subscribe here. Join readers around the world to be more swifty!
