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.