2011-08-26 79 views
0

嗨,大家好可有人请告知如何治愈内存泄漏下面的代码中内存泄漏,而使用的NSMutableArray

我已经尝试了关于释放和自动释放的每一个组合我能想到但每次要么时间的应用程序崩溃或泄漏保留

- (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". 
     [pickerView reloadComponent:1]; 


    } 

    //run the selector logic 
    [self textFieldDidEndEditing:currentTextField]; 

} 

希望有人可以告诉

千恩万谢

回答

2

你问题是这两条线:

newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]]; 
currentValues = newValues; 

第一行分配了一个新的NSMutableArray实例。第二行将指针从newValues复制到currentValues,覆盖指针值在currentValues。不管currentValues指向什么都丢失。这是泄漏。

您可以修复它是这样的:

newValues = [[NSMutableArray alloc] init... 
[currentValues release]; 
currentValues = newValues; 

这样一来,无论是指向currentValues有其引用计数递减将无法访问它。

您也可以通过将currentValues设置为Objective-C属性并使用self.currentValues[self setCurrentValues:]的访问器方法来解决问题;这些方法将为您处理保留/释放。

+0

嗨benzoda感谢您的建议,但我已经厌倦此版本之前,现在再次和应用程序崩溃与exc-bad-access当我滚动选择器它现在让我疯狂 – superllanboy

+2

你问了一个泄漏。这些答案会堵塞你的泄漏。崩溃是另一个问题。谷歌的指示,并在'objc_exception_throw'上放置一个断点,这样你就可以找出坏指针是什么。然后问一个新的问题,如果你不能*出*。 – benzado

+0

如果我采用你建议的用于插入漏洞的代码,崩溃会发生,可能是因为插入的漏洞可能导致另一部分代码崩溃?我真的不明白这一点,所以希望你可以详细说明并解释谢谢 – superllanboy

0

你NSMutableArray的分配是永远relea SED。

 
newValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]]; 

您应该autorelease或稍后发布它,当你知道你不需要它了。

+0

嗨亚历克斯我已经尝试autorelease但应用程序崩溃我已释放dealloc,但多数民众赞成在不停止仪器发现泄漏后 – superllanboy

0

不知道你有currentValues定义,但这应该不泄露工作:

在您的.h文件中:

@property (nonatomic, retain) NSArray * currentValues; 

在您.m文件:

@synthesize currentValues; 

self.currentValues = newValues; 
+0

嗨知觉currentValues分配在viewdidload像这样currentValues = [[NSMutableArray alloc] initWithArray:[pickerData objectForKey:[selectorKeys objectAtIndex:component0Row]]]; – superllanboy

+0

@superllanboy - is * currentValues *您的视图的属性或只是您在函数中声明的变量?如果它是后者,那么你发现你的泄漏。 – Perception

+0

hi知觉currentvalues是一个属性 – superllanboy