JLT JLT - 24 days ago 11
iOS Question

Understanding Retain Count In Objective-C Using Instruments(Leaks)

I am currently fixing memory leaks in our SDK. I am getting memory leaks mostly in strong references and class methods. Due to my lack of understanding in memory management, I find it hard to fix those leaks. I already read a lot about memory management but still I was not able to determine where the problems are located. So, I figured that I should know first how does balancing retain/release works just by looking at the code. As a result I switched off ARC did a little test.

This is my source code:

ViewController.h

@interface ViewController : UIViewController

@property (nonatomic, assign) IBOutlet UILabel *lLineOne;
@property (nonatomic, assign) IBOutlet UILabel *lLineTwo;

@end


ViewController.m

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *test = [[NSString alloc] initWithFormat:@"%@ %d", @"Test", 1];

_lLineOne.text = test;

_lLineOne.text = nil;
}

@end


I pretty much know that this will definitely cause a leak, because I didn't get to release
test
.

Then I use the instruments(leaks) to check the retain/release list. And here is what I got from the history of that string

enter image description here

I know that event#0 which is the malloc will increment the retain count to 1, then followed by setting that
NSString
to the property of UILabel will also increment the retain count by 1, so that gives us a 2. I guess the CFRetain is something that happens at a lower level in the code of NSString allocInitWithFormat but I am not sure why it contributes to another +1. Followed by that, what is that Retain in event#3? It seems that it is caused by UILabel, but I really don't have any idea about what it really is.

CRD CRD
Answer

First the standard warning: trying to track the retain count is not recommended, for the simple reason it is not in general possible for you to know what it should be.

You are seeking an answer you don't need. Most of the time all you really need to know under manual memory is if you create or retain you are responsible to arrange the release.

In your example you create the string, so you must arrange it's release after you no longer require it. UILabel may copy or retain at its choice, you don't need to know - you have to trust it follows the rules.

The "most of the time" above is largely to do with delegates. It is common for objects passed as delegates not to be retained by the callee, leaving the caller to keep the object around as long as the callee needs it.

HTH

Comments