iosnsurlsessionnsoperationqueuensoperationnsurlsessiontask

Advantage of wrapping NSURLSessionTask inside iOS NSOperations


Could any one please tell me what is the real advantage gained by using NSURLSessionTask inside NSOperation while making http network calls in iOS? We can get the abstraction by wrapping NSURLSessionTask inside any other plain custom class e.g APIRequest. What is the real motto behind using NSOperation for network calls? Thanks in advance.


Solution

  • My first inclination would be to say "none whatsoever", but after thinking about it a bit more, that's probably slightly too glib.

    In general, if your app already uses NSOperation for performing other tasks, it may be useful to have your network operations just be another special type of operation, so that you can kind of manage them in the same way. Of course, if you do that, you almost certainly shouldn't use NSOperation directly; instead, use a custom subclass of NSOperation that actually knows how to cancel the network operation when you call its cancel method. Using the NSOperation class as-is could be even worse than useless, if misused.

    The best explanation I have for why it is so common is historical. Apparently, a lot of programmers mistakenly believed that wrapping synchronous NSURLConnection requests inside of NSOperation objects gave them a way to cancel those requests. In reality, all it did was prevent the app from ever getting the data from the request, but the request continued until its completion. Unfortunately, in updating that code to use NSURLSession, that legacy baggage was often brought along for the ride, and is likely just as problematic now as it was then.

    As others have mentioned in comments, you could also ostensibly use operations to allow pending requests to continue after your app gets backgrounded, but in general, doing so is probably a mistake. After all:

    So really, the advantages to using a custom NSOperation subclass are the same as the advantages of using an NSOperation for anything else in your app — no more, no less.