Reputation: 12444
I am creating my NSURLConnection like so:
theConnection = [[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self];
I have looked in the NSURLConnection documentation and apparently the cancel API works for async requests, so will that work in the scenario?
Anyway, in my other class while the NSURLConnection is in progress I try to do this:
[mgr.theConnection cancel];
[mgr.theConnection release];
However, the delegate still gets called which I do not want. So how do I properly make sure I cancel the connection so that its delegate calls are canceled as well?
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
Upvotes: 5
Views: 7401
Reputation: 4952
The cancel
method does not guarantee that more delegate messages will not be delivered.
See the following which comes from the NSURLConnection class description:
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.
Upvotes: 0
Reputation: 41632
Obviously something is happening that is not clear. What I would suggest is adding some log messages to verify that in fact the timing is as 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");
I've had cancel in my code and its been tested for several years, no problems. I suspect you may learn something from the test above. I would be shocked to hear you get any messages after you see "Did cancel connection" on the console, but you might between the "Will" log and it.
EDIT: per your test, either mgr or mgr's theConnection property, is nil. This is the root cause of your problem. When you figure out why its nil and fix it, the connection will cancel and the same NSLogs will show no more delegate messages afterwards.
Upvotes: 4