Question

I have multiple classes that use NSURLSession, and they may run at the same time, is OK if I make them all NSURLSession delegates?

Code:

First delegate:

@interface userLoginScreen : UIViewController <UIAlertViewDelegate,  NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate>

Second delegate:

@interface syncDataOperation : NSOperation <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate>

Is it a good practice to do this?

Was it helpful?

Solution

All you're doing in your example there is saying "all these classes implement this interface", which is perfectly fine, and has no real bearing on what actually happens at runtime.

What I think you're getting at is those scenarios where you may want to have a single delegate object receiving delegate messages from multiple objects in an NSURLSession. For example, it's perfectly normal to have a single delegate handle callbacks for multiple NSURLSessionTask objects.

The only real problem might be if you were to have the delegate messages coming in on multiple different threads/queues. However, Apple have designed for that; when you create an NSURLSession object you can provide a specific delegateQueue for the callbacks to be sent on. This is the delegateQueue in sessionWithConfiguration:delegate:delegateQueue, for example.

If you don't provide one, NSURLSession "creates a serial NSOperationQueue object on which to perform all delegate method calls and completion handler calls", which is a very sensible default.

Tasks that you create under one NSURLSession will use that delegate queue for their delegate messages, too.

For example, if you create an NSURLSession without specifying a delegateQueue, it will create a serial queue for its delegate messages. If you then call downloadTaskWithRequest on it to create a NSURLSessionDownloadTask, the download task's delegate methods will use the same queue.

If you create thirty NSURLSessionDownloadTasks on it, all pointing at the same delegate, they'll all use the same queue to send their delegate messages, and because it's a serial queue, your delegate won't ever have two delegate messages arrive simultaneously, so you don't have to worry about coding to cope with that situation. (And all the delegate messages pass pointers to the related NSURLSession/NSURLSessionTask so you can tell which messages came from which tasks.)

Normally all the delegate objects you have to deal with a particular set of tasks will be dealing with tasks created underneath the same NSURLSession object, so everything uses the same delegate queue by default, and if you don't bother passing in a delegateQueue, NSURLSession, as I've said, provides a sensible one for you, so mostly the delegate stuff should Just Work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top