5

我正在创建我的 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
4

2 回答 2

4

显然正在发生一些不清楚的事情。我的建议是添加一些日志消息以验证实际上时间是否如您所想:

// 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”日志和它之间。

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

于 2012-08-17T23:22:56.327 回答
0

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.

于 2016-06-02T03:43:43.777 回答