Memory Management Tutorial for iOS

A memory management tutorial focusing on memory management – the first in a 3-part series. By Ray Wenderlich.

Leave a rating/review
Save for later
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Reference Count The Material

Let’s review what we’ve covered so far.

  • When you call alloc/init, you are returned an object with a retain count of 1.
  • So when you’re done with the object, you need to call release to decrement the reference count.
  • When you call a method that begins with anything except init or copy, you’re returned an object that will be autoreleased at some point in the future.
  • So if you want to use that object later, you need to call retain to increment the reference count.
  • If you create an object with alloc/init and want it to automatically be released at some point in the future for you, you can call autorelease on the object.

This should give you a handle of the basics of memory management in Objective-C. For more information, take a look at Apple’s Memory Management Programming Guide.

Where To Go From Here?

Here is a sample project we developed in the above memory management tutorial.

No matter how good of a developer you are and how well you understand memory management, you’re bound to make some mistakes and leak memory at some point. So my next memory management tutorial in this series covers how to debug memory leaks using XCode, Instruments, and Zombies. Get your ammunition ready!

Finally, check out the third article in this series, where I discuss Objective-C properties and how they relate to memory management, another area that I think is a common point of confusion for beginners.