Memory leaks while using NSMutableArray
Hi guys can somebody please advise how to cure the memory leaks in the code below
i've tried just about every combination of release and autorelease i can think of but every time either the app crashes or the leak remains
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//get refereance to the textfield
UITextField *currentTextField = (UITextField*)[self.view viewWithTag:200];
//check which picker
if(pickerView.tag ==1)
{
// Only calls the following code if component "0" has changed.
if (component == 0) {
// Sets the global integer "component0Row" to the currently selected row of component "0"
component0Row = row;
// Loads the new values for the selector into a new array in order to reload the data.
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]];
currentValues = newValues;
// Reloads the data of component "1".
[pickerV开发者_Go百科iew reloadComponent:1];
}
//run the selector logic
[self textFieldDidEndEditing:currentTextField];
}
hope someone can advise
many thanks
Your problem is these two lines:
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]];
currentValues = newValues;
The first line allocated a new instance of NSMutableArray. The second line copies the pointer from newValues
to currentValues
, overwriting the pointer value in currentValues
. Whatever currentValues
was pointing to is lost. That's the leak.
You could fix it like this:
newValues = [[NSMutableArray alloc] init...
[currentValues release];
currentValues = newValues;
This way, whatever was pointed to by currentValues
has its reference count decremented before you lose access to it.
You could also solve the problem by making currentValues an Objective-C property, and using the accessor methods via self.currentValues
or [self setCurrentValues:]
; those methods will handle retain/release for you.
Your NSMutableArray allocation is never released.
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]];
You should autorelease that or release it later on when you know you don't need it anymore.
Not sure how you have currentValues defined, but this should work without leaks:
In your .h file:
@property (nonatomic, retain) NSArray * currentValues;
In your .m file:
@synthesize currentValues;
self.currentValues = newValues;
精彩评论