Find Leaks in iOS Apps

Find Leaks in iOS Apps

We see in the article Memory management on iOS that the reference counter is managed manually.

An object is removed of the memory only when its reference counter is at zero.

NSMutableArray* myArray = [[NSMutableArray alloc] init];
myArray = nil;

In this snippet, the alloc increment the reference counter but then the labelmyArray is affected to nil.

We have an object with a reference counter greater than zero but we can’t access this object anymore because we don’t have a label to this object. The memory allocated for this object will never be freed.

A leak is not fatal to your app, but you should always try to avoid them. The worst case is to have a leak in a loop like in this example :

NSString* str=nil;
for (int i=0;i<2000000;i++){
str = @”my string”;
[str retain];
NSLog(@”%@”,str);
}

Because, depending of the size of your loop, you can leak a lot of data and saturate your memory (which is fatal to your app).

Instruments can help you finding these memory leaks.

(To launch it, in the Run menu of Xcode choose Run with performance tool and then Leaks )

Instruments will run your app and every few seconds check the memory for objects that are no longer accessible (leaked objects).

You can change this delay in the left panel : “sec Between Auto Detections”

To force the detection, you can click the button Ceck For Leaks Now.

The interface provides two lines. The first one is the number of allocations during the runtime.

This is the memory which is allocated for your objects, this value will only grows since it’s not decreased when you free an object.

The most important thing is the second line and the table below it.

You can see on this screen four leaks of a NSMutableArray. You can have more details on a leak by clicking on the third icon under “View” (left of “Library” and “Search”)

It give us the line where the leaked object was allocated but not where the las reference was lost.

The objective here is to use your app and test as many things as possible to discover leaks. For instance don’t forget to test when the connectivity is down.

NSObject which is the master object of everything have a method retainCountwhich can help you to find leaks.

mm
Steve Boullianne, Multiple post-graduate degrees, Mind/Body/Spirit enthusiast, & a member of Mensa. Loves Skiing, Scuba, and Food. Steve’s First job out of college was programming satellites for AT&T. Founded IPSOFACTO in 1996, Y2K boom, e-Commerce super success, 2.1 boom. Steve is ready to Mediate high quality for all life, our one planet, and human kindness. Loves to dance and tell jokes. Steve believes that Excellent Communication is key to human success (and failure). Steve has 3 sons who are his STARS. They will carry the world into a brilliant future. Since 1996, Steve has been a volunteer drug and alcoholism counselor in the Bay Area. The power of the Great Spirit is in you. Steve is a good friend to have.