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.
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.
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).
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);
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.
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];
}
Don't ever rely on retain counts directly. What's happened is that during the initialization process, some piece of code has retain
ed and autorelease
d the object. Because you can't tell how many times an object has been autorelease
d, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With