简体   繁体   中英

NSOperation Queue vs NSUrlConnection async

I have an app that is downloading several photos off of Flickr. Right now, all the photos are downloaded with a custom NSOperation class run on an NSOperationQueue .However, I have heard about NSUrlConnection async being more efficient, and was wondering which is better of this situation? Or, is there a third option that's even better than these two? The custom NSOperation simply calls [NSData dataWithContentsOfURL:] many times on different photos.

Using an approach which utilizes a subclass of NSOperation and which encapsulates NSURLConnection which is used in asynchronous mode (implementing the delegate protocols) is likely the most efficient, iff you additionally consider these aspects:

Ensure that the NSOperation subclass handles the delegate methods quickly , and that the underlaying thread (or the queue) will NOT be used to process the response data. Ideally, the delegate methods pass over the partial response data to another queue or thread where they are processed (note: image data may be preloaded on a background thread or a queue!).

The reason for this is that, the sooner the network operation finishes, the more requests can be performed per time. The network NSOperation shall be put into a NSOperationQueue whose max concurrent operations is set to 1, or 2. Rarely to 4 or higher. This setting depends on whether the server supports pipelining, and on the speed of the connection. Name that queue "Network bound queue".

The "data process" (preload image data) task is ideally a subclass of NSOperation, too. Likewise, the "data process" operations should be queued in a CPU bound NSOperationQueue. Per default the max concurrent operations of a NSOperationQueue is already suitable for CPU bound operations.

If you want to save the data to disk, again, ideally you create a NSOperation and queue those disk operations in a "disk bound queue". On devices, this seems not necessary, but if you have still such oldish "disks" - than it makes sense to set the number of max concurrent operations to the number of independent heads of the disk. ;)

Well, this all may make only a difference, when the connection is really fast and if you are able to process that much data in the same time. We are talking about 5 Mbyte per second on a device, and probably 25 Mbyte per second on a lab top.

I would recommend using AFNetworking ( AFNetworking on Github ) which has built-in functionality for queuing operations. If you only use it to load images that need to be displayed in a table view cell, you could use the AFNetworking category on UIImageView to load these images asynchronously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM