iOS Memory Management in Under 6 Minutes
Everything you should know about ARC in old good Objective-C.
iOS Memory Management in Under 6 Minutes
What you should know about ARC in old good Objective-C
In the last couple of days, I was searching more on memory management in iOS. It was a kind of a hard topic for me to understand in Swift. Therefore, I decided to go a little deeper in old good Objective-C — as I’m learning it already, to understand memory management more and get an in-depth understanding of that topic. Like, how was is it before the ARC? What happened after it? And what is the difference between ARC and Garbage Collector?… etc.
When you start working with objects, you will notice an interesting thing.
Objects are more demanding on memory than primitive types like integers and floats. This remains true whether these objects are from your own classes or they are objects you make from classes in any of the Apple frameworks.
Luckily we don’t have to worry about working manually with memory addresses and manually allocating or deallocating areas of memory (which is still true for some languages). Instead in Objective-C, we use something called reference counting.
What does reference counting mean?
When your application starts, an area of memory became available for your objects. So you create an object and an area of memory is claimed for that object. Now, the variable that holds the object is a pointer to that object. A pointer to an area of memory to be exact. What happens under the hood is that when the object was created it’s been given what’s called a retain count or a reference count and it represents the number of owners for a particular object. Therefore, we can imagine it to be one, as you see on the image below:
The variable that called var is a pointer to a block of memory. So, in your program, you work with that pointer and call methods on it as long as you want. But when you arrive at the end of the code block. This variable is no longer reachable or accessible by any part of the program. The retain count goes again to zero because there’s nothing pointing to that block of memory now. And when the retain count become zero the runtime engine says, here’s a block of memory that no one cares about. Therefore, it will release this block of memory and make it available to other objects to use.
What might go wrong?
The only issue here can be in situations when you are creating objects and passing them around from one place to another. So it’s not clear that the pointer is still in scope or not. And up until 2011 — when ARC (Automatic Reference Counting) was added, you had to write statements on when you were finished using that object.
Before ARC was added to Objective-C we would have to do something like this
MyClass *myObject = [[MyClass alloc] init];[ myObject myMethod]; // call methods... // doing some stuff with the object [myObject release]; // releasing the object
We’d write a little bit of code to create an object. It would be
created. We’d call methods of that object. But at some point, we would
have to actually explicitly call a
release statement. And that would be what was responsible for
taking a retain count down.
This is not a problem with a small number of objects. But when you had hundreds or thousands of objects being created, manipulated, used as parameters, passed from object to object… you had to keep track of them all. If you were passing an object from one area of your program to another, you might not even be sure if you could release it yet. Or if some other part of the program would take care of releasing it or might even release before you were done with it. So you could also write what was called, retain calls to that object. But you would still need to match any retain call up with an additional release call.
Basically, before ARC, you had to envision every possible scenario-logic that your application will go through to make sure that all of your objects’ lifetime is managed correctly. Not that easy.
Luckily, when using ARC you are no longer need to use
retain calls. But it’s
important to understand the dangers of incorrectly writing this code.
One of the problems you could have is you might release too soon. You’d create an object, have a pointer to that area of memory, you’d call the methods, at some point you’d release it. But if you still had a valid pointer, there’s nothing that would actually stop you writing another line of code that tried to use it. This would be called a dangling pointer. The pointer existed, but what it was pointing to was no longer valid in memory and this could cause a crash.
The flip side of this is you might not release at all, you might create an object. Start calling methods of that object and then just allow the pointer to drop out of scope and disappear. But you never released the object so you just started claiming more and more memory, what was referred to as a memory leak.
So having to write a lot of this code was certainly very prone to errors and issues. Now you might wonder if we’re using this new ARC feature why do I even mention the existence of things like release and retain calls. Because the idea of release and retain calls have not disappeared the language still does reference counting.
The language hasn’t changed. The difference is you simply don’t need to write the retain and release and autorelease calls because the compiler does. ARC is taking the fact that compilers have gotten so good, that any time you build your project, the compiler, in this case, llvm, which is what Xcode is using behind the scenes, is able to determine all the possible paths for your code. And it basically goes through your code synthesizing the write, retain, release, and autorelease calls that you would need.
What the compiler’s doing is effectively writing the same code you would write yourself if you were really, really, really good at writing memory management code.
ARC doesn’t physically change your source code files, but this is effectively what the compiler is doing when you compile a project, and you’re using ARC.
Difference between Garbage Collector and ARC
ARC is a very different effect than having a garbage collector. Languages that use garbage collection are often what is referred to as non-deterministic. It means that you can’t tell exactly when objects are being reclaimed because it’s being managed by the runtime by an external process. ARC allows us to be completely deterministic. The code controls when these objects are released. It’s just the code to release them has been written by the compiler, not by you. In fact, not only do you not write these calls when you’re using ARC, you can’t write these calls. If you try and do even the simple release call you’re going to get an error.
You need to be aware of the idea of retain or release. It is still what’s going on under the hood, but, certainly if you haven’t had to do it be thankful that you don’t have to do this anymore.
I’d love to hear more from you on that topic, and what do you think of going back to a language like Objective-C in order to understand a topic like memory management better? Have you ever done that before?
Tags: objective-c, iOS, memory-management | Edit on GitHub
14 Resources to help you get your iOS engineering job
How to pass iOS dev interview? I collected all useful resources to help you to prepare for the next interview and to get your first dream job…
How to get the first job as an iOS developer
Thanks to unDraw for great illustrations!
If you already read my last article on interviewing, you know that I failed dozens of my previous interviews. In that article, I mentioned how to improve developers’ hard & soft skills in order to impress a potential employer.
Please notice, some of them may seem overkill for you, but I think the complexity of the interviews may vary depending on your skills and what company you are applying for.
As far as I know, there are two categories of questions companies ask in the interview:
- Problem-solving questions
- iOS related question
I will be going through each of those and providing you with the resources that I find helpful.
The idea here is to solve as many problems as you can. I recommend two great books:
- Cracking the Coding Interview When you are preparing for interviews you should have a solid understanding of algorithms and data structures. After that, you should start with reading and doing the problems in Cracking the Coding Interview book.
- Elements of Programming Interviews You should start in Elements of Programming Interviews book after you have solved multiple questions from CtCI as the problems in this book are harder than those in the CtCI book.
You can also solve problems from websites like:
- LeetCode It’s a great website for solving whiteboard like questions.
- GeeksforGeeks I had an interview with Google once, and I found out similar questions to those that I interviewed in on websites like LeetCode and GeeksforGeeks. So, I really recommend checking those websites if you have a technical interview.
- HackerRank Interview Preparation Kit After I study a specific data structure. I solve problems from Cracking the Coding Interview book.Then, I solve easy to medium problems about the topic in which I’m studying from LeetCode. Finally, I might solve a problem or tow about the same topic from HackerRank’s Interview Preparation Kit.\ I do my best to try to solve from multiple sites as it opens my mind to different problems and strengthens my coding skills.
I’ve used this website multiple times and I highly recommend this website for practicing mock interviews with a real person.
- Pramp.com It’s really recommended to practice the interview style with someone of your friends. You can practice mock interviews on this website. I really recommend this website, for practicing an interview-like setting.
iOS related question
I personally haven’t used these books but I heard some very good feedback about them.
- Swift Coding Challenges Swift Coding Challenges book is one of Paul Hudson great books. It sets you the task of solving the most common questions you’ll get asked at coding interviews. You get hints in case you get stuck, then complete solutions so you can compare your results.
- The iOS Interview Guide This guide will help you prepare for your next interview by systematizing the learning, helping you refresh what you already know, and giving you answers to common iOS interview questions.
- Read Advanced Swift It’s a great book to learn more beyond the basics of Swift.
Sean Allen playlist helped me a lot in my interview, and honestly, I owe him a lot for that.
You can watch a video then try to also search online more about the topic he was talking about to help you get a deeper understanding of the topic.
An open source application for viewing Swift Algorithm Club markdown resources.
Using “be the compiler” tests. This will present you with 20 questions graded at three difficulty levels, and ask you to choose a correct answer. This is a highly technical test designed to hone your Swift knowledge. Also created by Paul Hudson.
If you are struggling to create iOS applications and can’t have a good resume because you are not a designer you can also buy some great iOS App Templates and if you are more interested in React Native App Templates you can buy them from here they have a really great collection.
Articles and Github repos
- RW Swift Interview Questions and Answers In this article, you’ll work through a series of Swift-specific interview questions and answers.
- How to get a job as an iOS developer A great article by Paul Hudson that really discuss deeply how you can get a job as an iOS developer.
- Awesome Interview Questions
Anyways, I wish you luck passing your next interview and getting your iOS engineering job.
Don’t forget to share with me any other resources that you found helpful in passing your interviews.
Tags: blogging, advice, interviews | Edit on GitHub