How to prevent leak on array with dictionaries used by CorePlot
This is a common case:
In code below (simplified), number of the dictionaries added to the array varies depending on size of data set (as usual). So it is impossible to match each dictionary with a corresponding 'release' statement. I assume releasing the array (in dealloc) would release all its enclosed dictionaries? Nevertheless, it produces a leak. How to eliminate it?// -----myController.h----
@interface ExerciseGraphController : UIViewController <CPPlotDataSource>{
NSMutableArray *plotDataForBar;
}
@property(readwrite, retain, nonatomic)NSMutableArray *plotDataForBar;
// -----myController.m----
- ...getPlotData... {
//Solution
if (plotDataForBar){
[plotDataForBar release];
}
plotDataForBar = [[NSMutableArray array] init];
//for each item in plotDataForBar {
... //Populates plotDataForBar with dictionaries.
[plotDataForBar addObject: [NSDictionary dictionaryWithObjectsAndKeys: // **LEAK** ( on __NSCFDictionary, __NSArrayM, and _GeneralBlock16)
[NSDecimalNumber numberWithFloat:xF], [NSNumber numberWithInt:CPBarPlotFieldBarLocation],
[NSDecimalNumber numberWithFloat:yF], [NSNumber numberWithInt:CPBarPlotFieldBarLen开发者_运维问答gth],
nil]];
}
} //Reads plotDataForBar in:
- ...numberOfRecordsForPlot...{ // Method required by CorePlot
return [plotDataForBar count];
}
- ...numberForPlot... { // " " " "
...
NSDecimalNumber *num = [[plotDataForBar objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
...
}
- ...dealloc {
[plotDataForBar release];
[super dealloc];
}
As much code is missing, only a guess:
Shouldn't you test in "...getPlotData..." if that property is already set, or release the old instance? This would be leaking every time this method gets called.
精彩评论