我正在创建我的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
答案 0 :(得分: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”日志和它之间收到消息。
编辑:根据您的测试,mgr或mgr的theConnection属性为零。这是您的问题的根本原因。当你找出为什么它的nil并修复它时,连接将被取消,并且相同的NSLogs将在之后不再显示委托消息。
答案 1 :(得分: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.