开发者

How to find the reference count of an object

I want to know the reference count of an obje开发者_Go百科ct in my program. Can I?


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.


You can, but you are wrong: you don't want to do that.


Isn't it meant to be...

[obj retainCount];


Never use retainCount, it does not work the way you think it does.

See: SO on finding retains/releases


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....


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜