Using operation queues with synchronous requests can be especially useful if you have many concurrent requests that you want to invoke. Operation queues make it easy to not only specify concurrent operation, but also to specify maxConcurrentOperationCount
to constrain how many concurrent operations you want to run (which is important if you're firing off a whole bunch of them as you're limited to how many can operate concurrently with a given server).
Your latter example, with initWithRequest
, is useful if you need the NSURLConnectionDataDelegate
methods (for any of a number of reasons, e.g. you want to update progress view, you want to perform some streaming operations, you want to be able to cancel connection, etc.).
A third approach is to marry the initWithRequest
approach with an NSOperationQueue
, namely to wrap the NSURLConnection
in its own NSOperation
. This marries these two techniques, providing the richness of NSURLConnectionDataDelegate
methods (cancelable, progress updates, etc.), with the power of operation queues (the ability to add network requests to queue for which you can configure degree of concurrency, establish dependencies between operations, etc.), but providing a nice interface. There are some idiosyncrasies to properly implement this approach (you have to schedule/create a runloop for NSURLConnection
if you use it in an NSOperationQueue
). I might, therefore, advise using a third party library, such as AFNetworking, if you want to enjoy the richness of this technique without getting lost in the implementation details.
In answer to your question of "which is best", it just depends upon what you're trying to do, as they all have pros and cons. But I prefer a NSOperation
-based NSURLConnection
, and would generally advise using AFNetworking if you want to simplify your development effort.
By the way, you can probably simplify the first example:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&_error];
}];