NSURLConnection的异步请求:何时发布

时间:2011-02-06 01:24:17

标签: objective-c cocoa nsurlconnection

Apple guide对于释放连接对象非常具体:它已在didFailWithErrorconnectionDidFinishLoading中完成。

然而,当我这样做时,我后来在zombi-mode中得到了这个

*** -[NSURLConnection releaseDelegate]: message sent to deallocated instance 0x1001045b0

似乎AppKit中有一些代码可以为我释放连接。

我很乐意认为Apple指南是错误的,但不希望出现一些可怕的内存泄漏,或者引入一些与旧OSX版本或类似内容的微妙不兼容。

在这种情况下忽略文档是否安全?

修改
代码创建请求

  URLConnectionDelegate *delegate = [[URLConnectionDelegate alloc] initWithSuccessHandler:^(NSData *response) {
      ...
  }];
  [NSURLConnection connectionWithRequest:request delegate:delegate];  

  // I do not release delegate when testing for this issue, not sure whether I should in general

委托类本身

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  successHandler(receivedData);

  [receivedData release];
  Block_release(successHandler);

  // do we really need this????????
  [connection release];
}

1 个答案:

答案 0 :(得分:3)

由于您已使用

创建了连接
[NSURLConnection connectionWithRequest:request delegate:delegate]; 

您没有该连接对象,因此您不应该释放它。

话虽如此,我不会推荐它。如果您没有对象,则无法保证它将超过自动释放池的耗尽周期,即,可能是您的连接对象在加载完成之前(自动)释放的情况。而是创建一个保留声明的属性来保存连接:

@property (retain) NSURLConnection *connection;

将您的连接对象分配给声明的属性:

self.connection = [NSURLConnection connectionWithRequest:request
    delegate:delegate]; 

并且,当连接完成加载或失败时,通过将nil分配给声明的属性来释放它:

self.connection = nil;

对于您的委托,如果只在连接加载时需要存在,您可以自动发布它,因为连接保留了委托:

URLConnectionDelegate *delegate = [[[URLConnectionDelegate alloc]
    initWithSuccessHandler:^(NSData *response) {
    // …
}] autorelease];

self.connection = [NSURLConnection connectionWithRequest:request
    delegate:delegate];