Reputation: 17541
I'm new to iPhone development, and I've just run my iPhone app throught the Intruments Leaks tool for the first time, and discovered a leak with my ListViewController dataArray method.
When I click on the listing it shows the code, and a few lines have percentages next to them. Presumably they're the lines that are leaking memory. I've pasted the code and the percentages below:
- (NSArray*) dataArray {
MapViewController *map = mainWindow.mainView.mapView;
NSMutableArray *data = [NSMutableArray arrayWithCapacity: 0]; /** REPORTS 25.3% HERE **/
if (selectedIndex == 1 || selectedIndex == 0)
[data addObjectsFromArray: DataSource.data]; /** REPORTS 7.4% HERE **/
if (selectedIndex == 2 || selectedIndex == 0)
[data addObjectsFromArray: DataSource.additionalData]; /** REPORTS 67.4% HERE **/
[data sortUsingSelector:@selector(compareAnnotation:)];
dataArrayNeedsUpdating = NO;
[data retain];
dataArray = data;
return data;
}
Is there anything I can change in that code to prevent the leak, or will changes need to be made in the calling code?
Thanks in advance,
Ben
Upvotes: 1
Views: 188
Reputation: 17906
If dataArray is storing a value when this method is called, it will leak, because you're not releasing the old value before you overwrite it. The simple solution is to use a setter (probably one generated by @synthesize) and change the lines
[data retain];
dataArray = data;
to the simpler (and more conventional)
[self setDataArray:data];
or, if you prefer,
self.dataArray = data;
The difference between
myMemberVariable = somePointerToAnObject;
and
self.myMemberVariable = somePointerToAnObject;
is one of the subtle gotchas for the new Objective-C coder.
Upvotes: 5