2011-06-06 45 views
0

我該如何解決這個潛在的泄漏?這個對象爲什麼是潛在的泄漏?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

NSUInteger row = [indexPath row]; 
Chapter *chapter =[Chapter alloc] ; 

switch (indexPath.section) { 
    case 0: 
     chapter = [einfuerung objectAtIndex:row]; 
     break; 
    case 1: 
     chapter = [vertiefung objectAtIndex:row]; 
     break; 
    case 2: 
     chapter = [spezial objectAtIndex:row]; 
     break; 
} 

if ([[NSFileManager defaultManager] fileExistsAtPath:[chapter urlOnFilesystem]]) { 

    dataInstance.chapter = chapter; 

    Container *container = [[Container alloc] init]; 
    [self.navigationController pushViewController:container animated:YES]; 
    [container release]; 
} 
else{ 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Kapitel nicht vorhanden" message:@"Kapitel wurde noch nicht heruntergeladen" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
} 

[chapter release]; 

} 

Xcode告訴我有關章的兩個問題。

  1. 此時不擁有的對象的引用計數遞減不正確。
    爲什麼這個對象不屬於我?

  2. 對象的潛在泄漏..(章節)
    如何正確釋放它?
    [chapter autorelease]]?

回答

4

你不應該在下面的語句中分配章節。

Chapter *chapter =[Chapter alloc] ; 

改爲使用下面的代替值。

Chapter *chapter = nil; 

我已經修改了你的代碼

NSUInteger row = [indexPath row]; 
Chapter *chapter = nil; 

switch (indexPath.section) { 
    case 0: 
     chapter = [[einfuerung objectAtIndex:row] retain]; 
     break; 
    case 1: 
     chapter = [[vertiefung objectAtIndex:row] retain]; 
     break; 
    case 2: 
     chapter = [[spezial objectAtIndex:row] retain]; 
     break; 
    default: 
     chapter =[[Chapter alloc] init]; 
     break; 
} 

if ([[NSFileManager defaultManager] fileExistsAtPath:[chapter urlOnFilesystem]]) { 

    dataInstance.chapter = chapter; 

    Container *container = [[Container alloc] init]; 
    [self.navigationController pushViewController:container animated:YES]; 
    [container release]; 
} 
else{ 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Kapitel nicht vorhanden" message:@"Kapitel wurde noch nicht heruntergeladen" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
} 

[chapter release]; 

} 
+1

@Jhaliya:你想在你的代碼引用中刪除'chapter'的第一個定義。 – DarkDust 2011-06-06 11:26:46

+0

@ DarkDust:明白了。現在更新了答案。 – Jhaliya 2011-06-06 11:30:03

+0

還有問題。如果你已經在默認情況下使用了,那麼你需要發佈。但在其他情況下,如果您從數組中獲取對象,則不應該釋放,因爲您不擁有該對象。 – taskinoor 2011-06-06 11:31:32

3
Chapter *chapter =[Chapter alloc]; 

您還沒有發送init但不是泄漏的原因。問題在於開關櫃。

chapter = [einfuerung objectAtIndex:row];

當你這樣做,你都指向一個新的chapter對象,而以前alloced一個被泄露。如果你總是從一個數組中獲得一個Chapter對象(即最多有三個部分),那麼你不需要alloc。只需聲明它,而且你也不需要再發布。

0

您首先分配一個對象並將其分配給chapter。你忘了初始化它,但這不是問題。

當您在switch語句中覆蓋chapter時會出現問題。對先前分配的對象的引用丟失,對象因此泄漏。

你需要做兩件事情:

  1. Chapter *chapter = nil;
  2. 在年底卸下[chapter release];既然你不是由[someArray objectAtIndex:row]返回的要素的所有者。