2011-08-26 82 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