2011-06-06 46 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]返回的要素的所有者。