I would like to know how many times an object has been autoreleased. I've used objective c long enough that it's generally straight forward to know whether an object has been autoreleased or not, however I constantly see questions dealing with memory and retain counts. At some point an answer always ends, "You can't trust the retainCount of an object" - which I agree with, BUT if you could determine how many times an object has been autoreleased, then you actually could trust the retainCount if you added a category like:
@interface NSObject (NSObject_MemoryDebugging)
- (NSUInteger) autoReleaseCount;
- (NSUInteger) retainCountWithAutoRelease;
@end
@implementation]
/** Determine how many times this object has been marked for autorelease **/
- (NSUInteger) autoReleaseCount;
{
// ??? not sure how to figure this out.
return 0;
}
- (NSUInteger) retainCountWithAutoRelease
{
NSUInteger retainCount = [self retainCount];
NSUInteger autoReleaseCount = [self getAutoReleaseCount]; // ???
return retainCount - autoReleaseCount;
}
@end
There would still be an exception for immutable types as those typically increase the retain count during a copy, so you still can't trust retainCount on those.
What I am NOT proposing
I am not seeking this answer to use retainCount in production code. However, I can see this as being valuable for someone debugging memory issues.
I imagine some people will HATE this question since programmers should not care about how many times an object has been autoreleased. Coding should be all about balancing allocs, retain, copy, new with release, end of story. However, the point of this is to help out people banging their heads. [NSObject retainCount]
burns a lot of people, and an answer to this question would be pretty cool.
I'm certain there's a way to determine how many times an object has been autoreleased. I just don't know what it is, hence the question.
See similar question: Objects inside NSAutoreleasePool in objective-c.
Edit
Thank you everyone for your answers. You may find this interesting => Ariel pointed out that GNUStep's implementation of Cocoa and specifically it's NSAutoReleasePool has this method: +(NSUInteger)autoreleaseCountForObject:(id)anObject. This method is slow, and only returns the autorelease count from NSAutoReleasePools on the callers thread. Still... It's interesting that its there. The docs cite that it is really only useful for debugging. This is really what I was hoping to find (or find possible) in the Cocoa framework somehow.
I agree with the answers given that even if it were possible to get the autorelease count that better tools exist (Zombies, Leaks, static analyzer).