I’ve been doing a lot interviews recently looking for new freelance opportunities. Most of those interviews have a deeper technical part questioning me on the foundations of iOS, Swift and programming.
You will always get the “explain ARC” one. Apple states:
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 do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.
Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.
Great, it just works! Great for programming, not so great for interviews. Luckily Apple provides more in detail information:
So, every time you create a new instance of a class, ARC keeps a record in memory of how may times the instance is used. When the instance is no longer needed, ARC will remove the record to free up memory
Just to be sure that ARC doesn’t remove objects that are still in use, it will only remove the record when there are no more active references to that object, i.e. the count is zero.
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 does not allow it to be deallocated for as long as that strong reference remains.
Unfortunately, strong references can cause memory leaks. If you assign nil to both john and unit4A, there still will be a strong reference between the two objects, preventing both from being freed from memory. Good to know there is a solution for this, weak references.
Remember this well, young padwan! You’ll need the next time you have an iOS interview. More interview questions were collected by Durul Dalkanat and can be found over at his medium account:
50 iOS Interview Questions And Answers #1
50 iOS Interview Questions And Answers Part 2
50 iOS Interview Questions And Answers Part 3
50 iOS Interview Questions And Answers Part 4
50 iOS Interview Questions And Answers Part 5