Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
When we talked about the basic Objective-C object class NSObject, we noted that memory is allocated with the alloc method and can subsequently be released with a release message. Unfortunately, it’s not always that simple. A running application can reference an object that you create in several places; an object also can be stored in an array or referenced by an instance variable someplace else, for example. You can’t free up the memory an object uses until you are certain that everyone is done using that object.
Luckily, the Foundation framework provides an elegant solution for keeping track of the number of references to an object. It involves a fairly straightforward technique called reference counting. The concept is as follows: When an object is created, its reference count is set to 1. Each time you need to ensure that the object be kept around, you increment its reference count by 1 by sending it a retain message, like so: