Reputation: 10961
When I use the dataTaskWithRequest:completionHandler:
API on NSURLSession
, do I have to keep a strong reference to the task I get back so it doesn't get deallocated before completing, or will the system hold onto it until it completes?
For example, is this OK:
[[[NSURLSession sharedSession] dataTaskWithRequest:myRequest completionHandler:
^(NSURLResponse *resp, NSData *data, NSError *err)
{
//do something with the response / data / error
}] resume];
Or do I have to do something like this:
//assume self.task is a retained property, and is set to nil in dealloc
self.task = [[NSURLSession sharedSession] dataTaskWithRequest:myRequest completionHandler:
^(NSURLResponse *resp, NSData *data, NSError *err)
{
//do something with the response / data / error
}];
[self.task resume];
I have code running in production with the first approach and am seeing no crashes because of it, but it's possible that it's sometimes silently failing because the task gets collected by the autorelease pool before it completes and thus never calls my completion block.
Upvotes: 2
Views: 438
Reputation: 10407
The session retains the tasks inside it until after the task completes (including calling any completion handlers). There's no need to retain it yourself.
Upvotes: 2