iosnsurlsessiondealloc

Object dealloc is not called if NSURLSessionTask resume is called


I have a NSObject class 'DataDownload_A' for downloading data. Inside I use NSURLSession and NSURLSessionTask. Now the problem is when I set this object to nil, the dealloc won't be called. Here is a segment code of DataDownload_A:

    NSString *urlString = [self URL];
    NSURL *url               = [NSURL URLWithString:urlString];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                            timeoutInterval:60.0];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    self.session = [NSURLSession sessionWithConfiguration:configuration
                                                 delegate:self
                                            delegateQueue:nil];
    self.receivedData = [NSMutableData data];

    self.task = [self.session dataTaskWithRequest:theRequest];
    [self.task resume];

And if I comment the last two lines 'self.task = [self.session dataTaskWithRequest:theRequest];' and '[self.task resume];', dealloc will be called. Therefore I assume there must be some issues when I use them. I tried to called '[self.task cancel]', 'self.task = nil', '[self.session invalidateAndCancel];' and '[self.session resetWithCompletionHandler:nil];' before I set my object to nil. But didn't help.

So does anyone know what the mistake I made ?? Would be grateful letting me know. Thank you in advance.


Solution

  • It looks like the URLSession holds a strong reference to its delegate. I found this line in the docs on URLSession:

    Important: The session object keeps a strong reference to the delegate until your app explicitly invalidates the session. If you do not invalidate the session, your app leaks memory.

    That bit makes it sound like a URLSession holds a strong reference to its delegate from the moment it's set up until it's invalidated or your app is terminated, but it may be that it only creates a strong reference when a data (or other) task is started.

    It sounds like you need to invalidate the URLSession in order to get it to release it's delegate. I suggest searching for that text in the URLSession docs in Xcode. Also search on "invalidate"