Chapter 9. Memory management


This chapter covers

  • Object lifetime management
  • Manual memory management via retain and release messages
  • Autorelease pools and the autorelease message
  • Object ownership rules
  • Memory management rules for custom classes

Many developers new to Objective-C find memory management one of the most difficult concepts to wrap their heads around. This is especially true for those coming from an environment such as Java, .NET, ActiveScript, or Ruby, where memory management is a much more automated, behind-the-scenes process.

In Objective-C all objects are created on the heap (unlike languages such as C++, which also allow objects to be placed on the stack). This means objects continue to consume memory until they’re explicitly deallocated. They aren’t cleaned up automatically when the code that uses them goes out of scope.

This feature has important connotations for how you program. If your application loses all references (pointers) to an object but doesn’t deallocate it first, the memory it consumes is wasted. This waste is typically called a memory leak, and if your application has too many memory leaks, it becomes sluggish or, in worst-case scenarios, crashes due to running out of available memory. On the other hand, if you deallocate an object too early and then reference it again, your application could crash or exhibit incorrect and random behavior.

9.1. Object ownership

9.2. Reference counting

9.3. Autorelease pools

9.4. Memory zones

9.5. Rules for object ownership

9.6. Responding to low-memory warnings

9.7. Summary