How to Manage Memory for iOS Apps

The easiest way to manage memory for iOS apps is to let the Objective-C runtime deal with it using a system called automatic reference counting (ARC) — please use it. (ARC has been available since 2011 in Xcode 4.2 or later.)

When iOS was first introduced, you had to manually manage memory by keeping track of the lifecycle of the objects in your program. You did so by telling the Objective-C runtime system when to retain and when to release objects, using a scheme Apple called manual retain-release, which in turn used a technique known as reference counting.

Although manually managing memory is certainly a nuisance, it is explained here because you will see it in older iOS programs, so you may as well be prepared. Here’s what you do. First, create a class that inherits from the root class NSObject in the Foundation framework. Your class then inherits three memory-management methods:

  • retain

  • release

  • autorelease

These three methods all manipulate a reference counter in the object that essentially tells the runtime system how many places in your program (or other objects) want to maintain a reference to the object.

Here is how this reference count is managed by the iOS:

  1. Every time retain is called on a target object, its reference count is increased by one.

    So, if five objects call retain on the target object, its reference count will be five (incidentally, when the object is allocated, init automatically increments the reference count).

  2. As they stop needing the target object, the five objects will call release on the object. Each time release is called, the reference count of the target object is decremented (by one).

  3. When the reference count becomes zero (that is, when the last object calls release), the object's memory is freed by the system.

The third method — autorelease — is called when an object you've created must be handed off to a thread and you want the thread to take care of freeing the object when the thread is done.

Internally, the ARC system uses the same reference counting system used for manual reference counting. However, to use ARC, you put your code in @autoreleasepool blocks like so:

@autoreleasepool{
… Your code …
}

The compiler inserts appropriate memory-management method calls into the code so that anything created within this @autoreleasepool block is freed when the program exits from the block.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com