Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C retain counts in dealloc

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?

like image 386
Michael Waterfall Avatar asked Jun 07 '26 06:06

Michael Waterfall


1 Answers

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.

like image 163
Jens Ayton Avatar answered Jun 09 '26 08:06

Jens Ayton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!