Memory Management and Automatic Reference Counting
In the first hour of this book, you learned a bit about the limitations of iOS devices as a platform. One of the biggies, unfortunately, is the amount of memory that your programs have available to them. Because of this, you must be extremely judicious in how you manage memory. If you’re writing an app that browses an online recipe database, for example, you shouldn’t allocate memory for every single recipe as soon as your application starts.
In the latest Xcode releases, Apple has implemented a new compiler called LLVM, along with a feature known as Automatic Reference Counting (ARC). ARC uses a powerful code analyzer to look at how your objects are allocated and used, and then it automatically retains and releases them as needed. When nothing is referencing an object, ARC ensures it is automatically removed from memory. No more retain or release messages to be sent, no more phantom crashes and memory leaks; you just code and it works.
For most objects you declare and use in a method, you do not need to do anything; when the method is finished, there are no more references to the object, and it is automatically freed. The same goes for variable properties you’ve declared with the weak attribute. Of course, it’s hyperbole to say that errors won’t happen with ARC; we have to use strong references in a few places in this book to keep iOS from deciding that we have finished with an object before we actually do.
When using a variable property that has a strong reference, you should tell Xcode that you’re finished using an object if you want it removed from memory. How do you do that? Easy: by setting its reference to nil.
For example, assume we’ve created a giant object called myMemoryHog:
To tell Xcode when we’re done using the object and let it free up the memory, we would type the following:
Once the huge object isn’t directly reference by any variables, it can be removed from memory, and all will be well with the world.
You’ve learned quite a bit in this hour’s lesson, and there are plenty of places for even the most experienced developer to make mistakes. As with everything, practice makes perfect, which is why our final topic focuses on a tool that makes practicing Swift fun.