Is there a way to fetch the current reference count for an NSObject (i.e. NSString)?
+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
2010-04-14 20:01:38
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
2010-04-14 20:04:38
Put a break point on the dealloc method.Also, check this link out: http://www.cocoadev.com/index.pl?NSZombieEnabled
JeremyP
2010-04-14 20:10:04
Better yet, use Instruments's Zombies template.
Peter Hosey
2010-04-14 20:18:20
If you're on 10.6, "Build and Analyze" in the Build menu may help point you at the problematic code.
Isaac
2010-04-15 02:27:43
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
2010-08-04 01:34:29
@Nate that's what Instruments is for...
Dave DeLong
2010-08-04 01:52:27