将委托(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)有一个特殊的考虑因素:它始终被保留。
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:DidFinishLoading
和 connection 中释放委托(delegate)(但您仍然必须释放连接): didFailWithError
方法。
关于iphone - 什么时候在 NSURLConnection 委托(delegate)上调用 release?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1632168/