【问题标题】:NSURLConnection Leaks -- Why?NSURLConnection 泄漏——为什么?
【发布时间】:2009-11-08 20:06:26
【问题描述】:

NSURLConnection *connection 是类的属性

@property (nonatomic, retain) NSURLConnection *connection;

Instruments 报告说我在下面代码的第二行中泄漏了一个 NSURLConnection 对象。

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];

didFinishLoadingdidFinishWithError 委托选择器中,我正在释放连接并设置为零

[self.connection release];
self.connection = nil;

我已经阅读了"NSURLConnection leak?" 的帖子和其他几个帖子。我觉得我一定错过了一些非常明显的东西。帮忙?

【问题讨论】:

  • 既然你的财产被保留了,为什么不分配给财产后立即释放连接呢?

标签: nsurlconnection


【解决方案1】:

正如 roe 的评论所说,您正在分配连接(保留计数 1),然后使用您的连接属性再次保留它(保留计数 2)。您只能在委托选择器中释放一次。你有两个选择:

1) 将连接属性更改为分配而不是保留。

@property (nonatomic, assign) NSURLConnection *connection;

// OR, since assign is the default you may omit it

@property (nonatomic) NSURLConnection *connection;

2) 在你的连接属性保留分配的对象后释放它:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = connection;
[connection release];
[request release];

选项 2 是首选,因为由于 alloc 和 release 尽可能靠近,因此泄漏的可能性较小。此外,如果您忘记释放之前的连接,合成方法将为您释放之前的连接。不要忘记在 dealloc 中释放 self.connection。

【讨论】:

  • 糟糕,我想说“正如鱼子所说的那样”。很高兴能提供帮助。
猜你喜欢
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 2023-04-08
  • 2011-03-21
  • 2015-07-05
  • 1970-01-01
相关资源
最近更新 更多