【问题标题】:Don't understand the potential leak不了解潜在的泄漏
【发布时间】:2023-07-13 20:16:01
【问题描述】:

我在 xcode 中使用了分析功能,我已经修复了除此之外的所有内容。

我想知道“分配的对象的潜在泄漏”究竟意味着什么,它指的是这些行。

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

self.type_prod = [[ProductType alloc] initWithNibName:@"ProductType" bundle:[NSBundle mainBundle]];

NSString *prodtitle = [product objectAtIndex:indexPath.row];
    type_prod.prodtitle = prodtitle;

 etc etc.

在这个空白的结尾我说:

    [[self navigationController] pushViewController:type_prod animated:YES];
[type_prod release];

那为什么说我最后放出来有可能泄露呢?

【问题讨论】:

  • [ProductType alloc] = 1 保留计数 self.type_prod + 1 [type_prod release] - 1
  • 我知道我的保留计数是 1,因为我分配,但因为我释放它,它将是 1-1=0(至少我是这么认为的)。但事实证明 self.type_prod 增加了它的保留计数 +1?
  • 我猜你的保留数是 self.type_prod 的 2 个,最有可能使用保留。
  • 我意识到我缺乏关于“自我”的使用以及它到底是什么的知识。我在这里使用它,但我不知道为什么我说 self.type_prod 而不是 type_prod.. 有人可以给我参考来理解这个概念吗?
  • self.type_prod = {some value} 等于 [self setType_prod:{some value}]。在你的代码中应该有'@property'、'@syntesize'。它们为属性生成 getter 和 setter。如果您使用“@property”(保留)...您将从 self.type_prod 获得额外的保留计数

标签: ios xcode memory-management memory-leaks


【解决方案1】:

我假设 type_prod 是一个保留属性。你需要在dealloc方法中用self.type_prod = nil释放它。

还要确保在所有情况下都执行最后的发布。立即自动释放它更安全:

self.type_prod = [[[ProductType alloc] initWithNibName:@"ProductType" bundle:[NSBundle mainBundle]] autorelease];

【讨论】:

  • 我像你说的那样放入了自动释放,在 void 的末尾我更改了 [type_prod release];到 self.type_prod = nil。因为我有一个自动发布,我假设我不需要在 self.type_prod = nil 之前发布,对吗?是否有必要有[type_prod release];在 -(void)dealloc 中?我很难理解自我的概念。
  • 如果你有我在回答中所说的自动释放,你不能在方法中再次释放 ivar。在 dealloc 中释放 self.type_prod = nil 是必要的。这与 [self setType_prod:nil] 相同。
  • 谢谢,我已经修好了!