views:

254

answers:

2

Is there a way to fetch the current reference count for an NSObject (i.e. NSString)?

+3  A: 

retainCount

Ben S
+11  A: 

As @Ben S said, it's the retainCount method. However, you're asking the wrong question, because:

Important: Typically there should be no reason to explicitly ask an object what its retain count is (see retainCount). The result is often misleading, as you may be unaware of what framework objects have retained an object in which you are interested. In debugging memory management issues, you should be concerned only with ensuring that your code adheres to the ownership rules.

So here's the real question: why do you need to know?

Dave DeLong
Somewhere in my ObjectiveC code a release was invoked on an already-released object. For some reason gdb will not break at the specific location where the memory access violation is occuring. I have a good guess where the problem resides but would like to verify my assumption by printing the refcount of the suspect object.
zer0stimulus
Put a break point on the dealloc method.Also, check this link out: http://www.cocoadev.com/index.pl?NSZombieEnabled
JeremyP
Better yet, use Instruments's Zombies template.
Peter Hosey
If you're on 10.6, "Build and Analyze" in the Build menu may help point you at the problematic code.
Isaac
You want to know, because you're trying to debug your application. You can't tell someone, "you don't need to know, because you should just do it right, in which case you won't care". Maybe they shouldn't need the code in their production release, but that's not the same thing as not needing to know the ref count, as a tool to debug why you're having problems. Bad answer.
Nate
@Nate that's what Instruments is for...
Dave DeLong