Reputation: 9
I want to know the reference count of an object in my program. Can I?
Upvotes: 0
Views: 426
Reputation: 902
Not sure why all the posts about not using retainCount, its been valuable in tracking down memory issues for me, now I wouldn't use it as a conditional, nor even understand how that would even be used, but you can add a simple category and use retain count adequately to determine lifetime usage of any given class.
@implementation replaceWithYourClassName (MemoryInspecting)
- (id) retain
{
NSLog(@"RETAIN: self [%@] : retain count [%d]", [self description], [self retainCount]);
return [super retain];
}
- (void) release
{
NSLog(@"RELEASE: self [%@] : retain count [%d]", [self description], [self retainCount]);
[super release];
}
And throw some breakpoints in there to track the context if that helps, as it often does.
Upvotes: 1
Reputation: 162712
Sure:
int referenceCount = rand();
The real answer, of course, is the retainCount
method; NSUInteger rC = [someObject retainCount];
. However, the value returned by it is useless.
never never use the retain count in a conditional
the retain count can never be zero
the retain count never reflects whether or not the object is autoreleased
a retain count of 2-bazillion is perfectly reasonable for some classes some of the time
the retain count for any object that passes through system API may be a seemingly random value within indicating a problem
Bottom line: If you treat the retain count as an absolute value, you are doing it wrong. You either increase or decrease the retain count through your code, Keep your plusses and minuses in balance, and you are doing it right.
Upvotes: 6
Reputation: 11053
As everybody said, you can, BUT DON'T USE IT.
Back when I started I also thought that using the ref count I could find my memory problems easier. I wasted TOO MUCH time. The number you get is simply wrong in the sense that you can not (easily) just use it to find your memory management issues.
It is by far better to really check all the manually created objects with alloc, new, and your manual retains.
Simply sit back and focus onthe question "Who has ownership of this variable?" All thouse will keep your var alive. Also be sure to set your ivars with self.ivar, otherwise the ownership to the object will not be set.
But the easiest is to just use ARC in the newest version. This takes care of (most) of all these questions....
Upvotes: 1
Reputation: 112857
Never use retainCount, it does not work the way you think it does.
See: SO on finding retains/releases
Upvotes: 1