gpt4 book ai didi

objective-c - NSURLConnection 的异步请求 : when to release

转载 作者:行者123 更新时间:2023-12-03 17:36:27 24 4
gpt4 key购买 nike

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

然而,当我做同样的事情时,我后来在僵尸模式下得到了这个

*** -[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

委托(delegate)类本身

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

[receivedData release];
Block_release(successHandler);

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

最佳答案

自从您与以下人员建立联系以来

[NSURLConnection connectionWithRequest:request delegate:delegate]; 

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

话虽如此,我不推荐它。如果您不拥有某个对象,则无法保证它会比自动释放池耗尽周期更长,即您的连接对象可能在完成加载之前被(自动)释放。相反,创建一个保留声明的属性来保存连接:

@property (retain) NSURLConnection *connection;

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

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

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

self.connection = nil;

对于您的委托(delegate),如果它只需要在连接加载时存在,您可以自动释放它,因为连接保留委托(delegate):

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

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

关于objective-c - NSURLConnection 的异步请求 : when to release,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4910902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com