gpt4 book ai didi

ios - 正确取消NSURLConnection?

转载 作者:可可西里 更新时间:2023-11-01 04:42:23 24 4
gpt4 key购买 nike

我正在这样创建我的 NSURLConnection:

theConnection = [[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self];

我查看了 NSURLConnection 文档,显然取消 API 适用于异步请求,那么它在该场景中是否有效?

无论如何,在我的其他类(class)中,当 NSURLConnection 正在进行时,我尝试这样做:

[mgr.theConnection cancel];
[mgr.theConnection release];

但是,委托(delegate)仍然被调用,这是我不希望的。那么我如何正确地确保取消连接,以便它的委托(delegate)调用也被取消?

控制台:

2012-08-17 23:01:11.820 app[14097:707] Will cancel connection=(null)
2012-08-17 23:01:11.821 app[14097:707] Did cancel connection
2012-08-17 23:01:11.821 app[14097:707] Did release connection
2012-08-17 23:01:20.330 app[14097:707] didReceiveResponse
2012-08-17 23:01:20.331 app[14097:707] didReceiveData
2012-08-17 23:01:20.332 app[14097:707] connectionDidFinishLoading

最佳答案

显然,有些事情正在发生,但还不清楚。我的建议是添加一些日志消息来验证时间是否如您所想:

// Add a simple log like (NSLog(@"%@", @"conn_del"); to all your delegate methods)

Then addend you cancelation code with this:
NSLog(@"Will cancel connection=%@", mgr.theConnection);
[mgr.theConnection cancel];
NSLog(@"Did cancel connection");
// [mgr.theConnection release]; assuming a retained property, this is not the way to do it
mgr.theConnection = nil; // this is the proper way - release and nil out the property
NSLog(@"Did release connection");

我已经在我的代码中取消了,并且已经测试了几年,没有问题。我想您可能会从上面的测试中学到一些东西。如果您在控制台上看到“Did cancel connection”后收到任何消息,我会感到震惊,但您可能在“Will”日志和它之间。

编辑:根据您的测试,mgr 或 mgr 的 theConnection 属性为零。这是您问题的根本原因。当您弄清楚为什么它为 nil 并修复它时,连接将取消并且相同的 NSLogs 之后将不再显示委托(delegate)消息。

关于ios - 正确取消NSURLConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12012631/

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