Effective Objective-C 2.0

Understand Reference Counting

How Reference Counting Works

Under reference-counting architectures, an object is assigned a counter to indicate how many things have an interest in keeping that object alive. A method to inspect the retain count, called retainCount, is generally not very useful, even when debugging, so I (and Apple) encourage you not to use it. The following three methods declared on the NSObject protocol can manipulate that counter to either increment it or decrement it:

  1. retain Increment the retain count.

  2. release Decrement the retain count.

  3. autorelease Decrement the retain count later, when the autorelease pool is drained.

features

  1. A method to inspect the retain count, called retainCount, is generally not very useful, even when debugging, so I (and Apple) encourage you not to use it.

  2. Objects are said to own other objects if they hold a strong reference to them. This means that they have registered their interest in keeping them alive by retaining them

  3. In Objective-C, a call to alloc will result in the return of an object that is said to be owned by the caller. That is to say, the caller’s interest has already been registered because it used alloc.

  4. However, it is important to note that this does not necessarily mean that the retain count is exactly 1. It might be more, since the implementation of either alloc or initWithInt: may mean that other retains have been made on the object. What is guaranteed, though, is that the retain count is at least 1. You should always think about retain counts in this way. You should never guarantee what a retain count is, only what effect your actions have had on the retain count: whether that is incremented or decremented.

Memory Management in Property Accessors

- (void)setFoo:(id)foo
{
    [foo retain];
    [_foo release];
    _foo = foo;
}

The new value is retained, and the old value is released. Then the instance variable is updated to point to the new value.

Autorelease Pools

- (NSString*)stringValue
{
    NSString *str = [[NSString alloc] initWithFormat:@"I am this: %@", self];
    return [str autorelease];
}

Since the release from being in the autorelease pool won’t happen until next time around the event loop, So autorelease is a way of extending the lifetime of an object just enough so that it can survive across method call boundaries.