Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding who has a retain count to an object

I have a UIViewController which has a retainCount of 3 the moment I instantiate it. That stirs me as terribly incorrect. What's the best way of figuring out who bumped up the retainCount to 3? I'd imagine instantiating the object should give the pointer 1, then I suppose maybe pushing it onto the UINavigationController's stack might bump it up one (not sure about that though?), but the third.. is a mystery.

like image 818
Coocoo4Cocoa Avatar asked Feb 25 '09 15:02

Coocoo4Cocoa


People also ask

What is retain count?

The retain count is an internal count maintained by an object: how many times an unbalanced retain has been sent to that object. The reference count is an external fact: how many objects have a reference to this object. The goal of memory management, at heart, is to keep those two numbers the same at all times.

How do I find the retain count in Swift?

You can always check the reference count of a variable by using the CFGetRetainCount function. Note: Reference counting is done only to manage memory for reference types (e.g., classes and closures).

How do I find reference count in Objective C?

You can do this by putting break points or using print(CFGetRetainCount(CFTypeRef!)) function in your code . You can also increment the reference count of an Object using the CFRetain function, and decrement the reference count using the CFRelease function. CFRetain(CFTypeRef cf);CFRelease(CFTypeRef cf);

What is retain count in IOS?

An essential concept in ARC is the retain count, which is a number that keeps track of how many objects are “holding onto” to another object. ARC only applies to reference types such as classes, and not to value types like structs.


2 Answers

Adam is right that you shouldn't be overly concerned about retain counts.

But if you ever have a legitimate need for solving such a mystery, a good technique is to subclass the affected class just so you can add overrides to the memory-management methods.

E.g. in a subclass of UIViewController, you could implement:

- (id) retain
{
    // Break here to see who is retaining me.
    return [super retain];
}
like image 85
danielpunkass Avatar answered Nov 15 '22 12:11

danielpunkass


Don't ever rely on retain counts directly. What's happened is that during the initialization process, some piece of code has retained and autoreleased the object. Because you can't tell how many times an object has been autoreleased, you don't actually know what the real retain count is.

Retain counts should only be used as a debugging aid, never as program control flow.

As long as you follow all of the rules laid out in the Memory Management Programming Guide for Cocoa, you won't have problems.

like image 37
Adam Rosenfield Avatar answered Nov 15 '22 11:11

Adam Rosenfield