正确取消 NSURL 连接



我正在像这样创建我的NSURLConnection:

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

我已经查看了 NSURLConnection 文档,显然取消 API 适用于异步请求,那么在这种情况下会起作用吗?

无论如何,在我的另一堂课中,当 NSURLConnection 正在进行时,我尝试这样做:

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

但是,代表仍然被调用,我不想要。那么,如何正确确保取消连接,以便其委托调用也被取消呢?

安慰:

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");

我已经在我的代码中取消了,并且已经测试了几年,没有问题。我怀疑你可能会从上面的测试中学到一些东西。在控制台上看到"确实取消连接"后,听到您收到任何消息,我会感到震惊,但您可能会在"Will"日志和它之间。

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

cancel 方法不保证不会传递更多的委托消息。请参阅来自 NSURLConnection 类说明的以下内容: The -cancel message hints to the loader that a resource load should be abandoned but does not guarantee that more delegate messages will not be delivered. If -cancel does cause the load to be abandoned, the delegate will be released without further messages. In general, a caller should be prepared for -cancel to have no effect, and internally ignore any delegate callbacks until the delegate is released.

最新更新