iphone - 什么时候在 NSURLConnection 委托(delegate)上调用 release?

标签 iphone ios delegates nsurlconnection

将委托(delegate)传递给 NSUrlConnection 对象时,如下所示:

[[NSURLConnection alloc] initWithRequest:request delegate:handler];

你应该什么时候调用委托(delegate)的释放?它应该在 connectionDidFinishLoading 中吗?如果是这样,我将不断收到 exec_bad_access。我看到我的委托(delegate)正在通过仪器泄漏。

谢谢

最佳答案

取 self 的blog post这里:http://i.ndigo.com.br/2012/01/releasing-nsurlconnection-and-its-delegate/


您必须特别注意委托(delegate)对象,因为对于 NSURLConnection,委托(delegate)有一个特殊的考虑因素:它始终被保留。

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/doc/uid/20001697-BAJDDIDG

initWithRequest:delegate:

Special Considerations: The connection retains delegate. It releases delegate when the connection finishes loading, fails, or is canceled.

因此,考虑到这一点,您有多种选择来确保正确释放您的委托(delegate),我将尝试解释 2 个简单的选项。

第一种也是最常用的方法是使用与委托(delegate)相同的类来初始化 NSURLConnection。

[[NSURLConnection alloc] initWithRequest:request self];

通过这样做,您的类的保留计数将在连接启动时增加 1,然后在连接完成加载、失败或取消后减少 1,从而不会导致内存泄漏。

第二个选项,即您尝试执行的选项,是使用另一个对象来处理所有连接调用。这也很好用,但你需要特别注意内存力。要解决您的问题,您可以做的一件简单的事情是使用自动释放对象初始化连接。

//creates the handler object
MyHandlerClass *handler = [[MyHandlerClass alloc] init];

//creates the connection with handler as an autorelease object
[[NSURLConnection alloc] initWithRequest:request delegate:[handler autorelease]];

或者您可以在创建连接后立即释放您的处理程序(因为它已被连接保留)

//creates the handler object
MyHandlerClass *handler = [[MyHandlerClass alloc] init];

//creates the connection with handler
[[NSURLConnection alloc] initWithRequest:request delegate:handler];

//releases handler object
[handler release];

这两种方式都将处理程序对象所有权仅保留给连接类,连接类将在完成加载、失败或取消后立即释放处理程序对象,再次导致没有内存泄漏。

编辑:通过执行上述任何选项,您不必担心在 connection:DidFinishLoadingconnection 中释放委托(delegate)(但您仍然必须释放连接): didFailWithError 方法。

关于iphone - 什么时候在 NSURLConnection 委托(delegate)上调用 release?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1632168/

相关文章:

iphone - 为什么我的 CLLocationmanager 委托(delegate)没有被调用?

iphone - 如何打开从 UIWebView 到新 UIWebView 的任何链接?

iphone - 如何在 MFMailComposeViewController 上向正文添加换行

ios - 模态视图 Controller 动画状态恢复

使用 SOAP 的 IOS Swift 调用 Web 服务

ios - 想要创建一个监听器来检测整个应用程序中的 viewWillAppear 调用

JavaScript 重复委托(delegate)创建

c# - Lambda 事件处理程序范围

iphone - 像 Notes 应用程序中的动态标题

iphone - 当属性设置太早时 UIImageView 不显示图像