views:

75

answers:

2

I'm seeing something fairly strange here, I've got breakpoints set in various dealloc methods in my app, and on inspection, the retain counts of the object self varies from 1 to 0. When dealloc is called, will the retain count of the object be set to 0 already?

I'm using print (int) [self retainCount] in the console to test this.

The 0's seem to only appear in the dealloc of my NSOperation's that are being run in an NSOperationQueue.

Any idea why this is?

+6  A: 

The retain count of your object doesn’t matter in -dealloc. For practical purposes, it’s undefined.

The normal implementation of reference counting uses an external reference count for values greater than zero – see NSIncrementExtraRefCount() and NSDecrementExtraRefCountWasZero(). When the extraRefCount count is zero, the refCount is one. When NSDecrementExtraRefCountWasZero() is called and the extraRefCount is already zero, it returns YES and -dealloc is called. Except when dealing with the return value of NSDecrementExtraRefCountWasZero() there is no way to distinguish a refCount of one from a refCount of zero.

That NSOperation gets a zero refCount suggests it’s not using the normal mechanism.

Ahruman
Beyond not mattering in `-dealloc`, if a `retain` exists when `dealloc` is called, your program is already dead and has been for a while prior to that call.
bbum
A: 

I'm not quite sure how objective-c handles this but if the dealloc method is being called, it means the retain count has hit 0 so object should be released from memory. There's no other way around it, if your object has a retainCount of 2 and you call [obj release] once, your dealloc method will never be called - so if your breakpoints are being hit and written to the Log then you can be sure that the object is on its way to being destroyed

Remember that your object will subclass NSObject so you should be putting a [super dealloc] call in your dealloc method too.

djhworld