我该如何解决这种潜在的泄漏?
- (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告诉我章节的两个问题。
此时不拥有的对象的引用计数的不正确递减。
为什么这个对象不属于我?
物体的潜在泄漏..(章)
如何正确释放?
[章节autorelease]]?
答案 0 :(得分: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 :(得分:3)
Chapter *chapter =[Chapter alloc];
您尚未发送init
,但这不是泄密的原因。问题出在交换机箱中。
chapter = [einfuerung objectAtIndex:row];
当你这样做时,你指向一个新的chapter
对象,并且先前分配的对象被泄露。如果您总是从数组中获取Chapter
对象(即,您最多有三个部分),那么您不需要alloc
。只需声明它,你也不需要发布它。
答案 2 :(得分:0)
首先分配一个对象并将其分配给chapter
。你忘了初始化它,但那不是问题。
当您在switch语句中覆盖chapter
时会出现问题。对先前分配的对象的引用将丢失,并且对象因此泄露。
你需要做两件事:
Chapter *chapter = nil;
[chapter release];
,因为您不是[someArray objectAtIndex:row]
返回的元素的所有者。