views:

196

answers:

1

Within tableView:cellForRowAtIndexPath:

// Make a cell:
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero     reuseIdentifier:@"Default"] autorelease];

// Make a spinner:
UIActivityIndicatorView *spin = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
// [spin retainCount] = 1

// Start spinning
[spin startAnimating];

[cell.contentView insertSubview:spin atIndex:0];
// [spin retainCount] = 3. Huh?
// I would have expected it to be 2 at this point.

[spin release];
// [[cell.contentView.subviews objectAtIndex:0] retainCount] = 2

At this point I would have thought cell.contentView.subview is the sole object with a retain on the spinner. But clearly a retain count of 2 indicates that something else is also retaining it. Could someone please explain to me who the mystery object is that has a retain on the spinner besides cell.contentView's subview array?

Cheers,

Doug

+2  A: 

The mystery object that retains your spinner (and lot's of other objects) is called NSAutoreleasePool.

In Cocoa, it's quite useless to look at an objects retainCount, since you cannot know if the object has been retain-autoreleased before (often many times). The retainCount will only decrement after the current pool is drained, usually after the next pass through the run loop. If you do not retain the object it will be deleted when the pool is drained.

So again, the basic rule of thumb is: Do not look at the retainCount.

If there was an autoreleaseCount method it would be possible to calculate the "logical" retain count, but I'm afraid Apple's engineers left this as an exercise for beginning Cocoa developers ;)

Nikolai Ruhe
Actually, for objects I'm not autoreleasing, retainCount has never been wrong for me. I used it frequently and reliably. I'm not sure I agree with your assessment in the general case, but in this particular case I think you are probably correct. UITableView and UITableViewCell get up to all manner of trickery under the hood.
dugla
You don't have to autorelease the objects yourself, it can be some code not under your control. Cocoa and Cocoa-Touch make use of autoreleased objects everywhere. For example, synthesized getters of (atomic, retain) properties do this to assure objects are alive when the getter returns. And there are other places I'm sure you're not aware of.
Nikolai Ruhe