Correctly cancel NSURLConnection?

I create my NSURLConnection like this:

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

I looked at the NSURLConnection documentation and obviously the undo API works for async requests, so will this work in the script?

Anyway, in my other class while NSURLConnection is running, I'm trying to do this:

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

However, the delegate still receives a call that I do not want. So, how to make sure that I canceled the connection so that its delegated calls are also canceled?

Console:

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
+5
source share
2 answers

Obviously, something is happening, which is not clear. I would suggest adding a few log messages to make sure that the actual timing is what you think:

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

, , . , - . , , , " " , "" .

EDIT: , mgr mgr theConnection property, . . , nil , , NSLogs .

+4

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.

0

All Articles