Swift Memory Management: A Simple Guide
Does “memory management” come up in iOS interviews? Yes, it does! Let’s break it down.
What’s Memory Management?
Memory management means making sure your app uses memory wisely. We want an app to use just what it needs.
Why Does It Matter?
An app that uses too much memory can go wrong. It can crash, and users won’t like that. It could lead to bad reviews and even loss of money for the business.
How Does iOS Handle Memory Management?
Swift uses a helper called Automatic Reference Counting (ARC) to manage memory.
What’s ARC?
ARC stands for Automatic Reference Counting. It takes care of memory so you don’t have to. Here’s how it works:
- When you create an object, ARC sets aside some memory. The object’s reference count goes up by one.
- If you assign the object to a variable, constant, or property, ARC bumps up the reference count by one. We call this a “strong reference”. It means the object won’t go away as long as there’s a reference to it.
- When a strong reference to an object is removed or released, ARC lowers the object’s reference count by one.
- When the count hits zero, the memory is freed up.
Types of Memory in Swift
There are two main kinds of memory:
- Value types
- Reference types
Let’s look at both.
Value Types
With value types, ARC doesn’t change the reference count. Values are copied, not “pointed to”. When a value isn’t needed, the memory is freed up.
Reference Types
Reference types are instances of classes. They’re assigned to constants, properties, and variables. ARC watches these strong references.
- Assigning a value makes the reference count go up.
- Unassigning it makes the count go down.
- If the count hits zero, the memory is freed up.
Watch out for strong reference cycles! That’s a story for another post.
Wrapping Up
I hope this post helped! If you have an interview coming up, grab my free iOS Interview Cheat Sheet below!