Memory Management in iOS
Memory Management in iOS
Memory Management in iOS

Audience
This post is for those who are having little to zero knowledge in memory management. Most people skip the deep basics of this topic as it’s sometimes complicated. But, memory management is quite important to understand as it is the thing which enables and handles all the allocations, initializations of Objective C Objects, Swift Objects. So, if you want to learn and practice memory management with real examples, this post will help you in getting the best.
What is Memory Management?
Memory management is all about managing and handling all the allocations, your app creates during its lifetime. In any platform, the operating system handles the memory management for the application. In Java, JVM and garbage collector takes the ownership of removing and reclaiming the memory for the objects, the application wants to create. Just like that, we have Automatic Reference Counting in iOS. It handles all the allocations the app creates, destroying all the objects which are not in use or will not be used throughout the lifetime of the app.
All the objects will be created on the RAM based on the available space it has. Operating system gets the instruction from the app to allocate memory for the object, it creates it and sends back the address of the memory, which you use to create a reference and change the values when required.
How is memory allocated?
Look at this statement:
In the first line, the app creates a memory in RAM to hold the string value and tempString now owns this memory. If you try to print tempString it instead of printing the address it prints the content in the memory it is referencing. This is the way Objective C and Swift variable works which is quite opposite of C pointers. If we have to print the address then we have to first take the unsafePointer to that type and then we can have the address pointer to that location.
How is Memory Management in iOS handled?
Initially, Memory management in iOS used to be handled using non-ARC, where we used to retain and release objects manually throughout its whole lifecycle. Now, it supports ARC and we don’t have to retain and release the objects manually. Let’s understand the ARC first.
Automatic Reference Counting(ARC)
Just like JVM in Java, iOS has ARC to handle its memory management. It’s actually better than JVM in some areas, that’s why it is considered to be the best in the market. ARC works on reference counts on objects, It releases the objects from the memory if the object is having reference count to 0. Now you might be wondering how this reference count works. No problem. You will get your doubts cleared in the next example.
class Person{
var name: String!
init(name: String) {
self.name = name
}
deinit{
print("Person with Name \(name) is being deinitialized" }
}
We have created Person Class with name property, an initializer with name and a deinitializer.
var person1: Person? = Person(name: "Jacky")
Here we created a Person object with the initializer. Now person object is created somewhere in the memory, your app doesn’t know it yet and can not access it. To get the access of the object it just created, we actually assign the strong reference back to the person1 variable. Now this person object in memory has reference count to 1.

Look at another example…
var person1: Person? = Person(name: "Jacky")
let person2 = person1
Now in this example first line create one reference to the person with the name Jacky. In the second line we are passing a reference to another variable which makes the reference count 2 on the person object.

So even if you say
person1 = nil .
print("Person2 is \(person2.name!)") .

when person1 gets nil, it decreases the reference count on the object which makes the total count to 1. As person2 is still having a strong reference to the person object, the object can’t be destroyed until person2 also releases it.
Note: By Default, the reference type is always strong for a property
Only One Rule — An instance from the memory gets purged out if the reference count on the object is zero or no variable is owning this instance.
Reference Types
Weak
Before understanding Strong reference types, let's understand the weak first.
As the name suggests, a weak reference maintains a weak reference to the instance in the memory. It does not increase the reference(retain) count on the instance hence does not own the object. if all other strong references on the instance have been released, then the instance gets destroyed from the memory. In that case, this weak reference points to the instance which is already destroyed from memory and so nil value will be assigned to the variable, that’s why the compiler does not allow us to create a weak reference with let constant as it might change it’s value to nil in no instance case.


Strong
A strong reference increases the reference count on the object and owns it. The object can not be destroyed from the memory until the variable releases it’s ownership.
cityObj = nil

After releasing the ownership by citiObj, reference count on City object gets to 0 which makes it eligible to be cleared by ARC from the memory
Unowned
An unowned reference is similar to weak reference in a way that it doesn’t increase the reference count on the object. Unlike weak references, unowned references don’t have to be optional as it doesn’t get to nil automatically after deallocation. So use unowned references when you are sure that the object will not be destroyed throughout the variable lifetime. If we try to access the object which is already been destroyed from the memory then the programme crashes as it doesn’t have any value, not even nil.
Weak Vs Unowned
See what Apple says about it
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 initialisation:
Source Apple Documentation
Summary
That’s it. I am sure we now have a basic understanding of how these allocations and deallocations work in iOS. We now have a basic idea where to use Strong, Weak, Unowned references based on the programme requirement.
Source. Apple Documentation