I have an NSOperationQueue, in which I keep on adding NSOperation objects that hit server and brings data. Is there a way to store the received data in the order in which they were fired? For example, suppose the A, B and C objects are added in NSOperationQueue in the order ABC. Now each of the three A, B and C will bring data in their corresponding threads. I want to store the results in the same order in an array so that the contents of array becomes "Result A", "Result B" and "Result C". Please provide a so开发者_开发知识库lution or a direction towards the right answer for this problems. Thanks Guys
EDITED - Basically, I want to design an autosuggest component which brings data from server (same as in google app), and I thought NSOperationQueue to be the best method to implement this. Currently I set the maxConcurrentOperationCount to 1, but I want to set it to more than 1, as data comes from the server very slowly. Please point out the right solution or direction towards this question. Thanks
If you're using 1 op at a time, then simple NSURLConnection
would do that with NSURLRequest
and delegate methods. No need to create operation queue with operations
UPDATE: If you'd like to download single resource and use parallel downloads for this - see this question/answer.
Instead of using different hosts you'd define same host for different NSURLRequests/NSURLConnections and add extra "Range" http header to define the data range of requested file. Afterwards all operations were complete and data was gathered into, say, array, just sort data objects by Range they were requested with and concatenate it.
Give each piece of data a value when you create them. You can pass the index into your NSOperation class and when you get a response, wrap the data in a class of your own and give it the index)
@class MyData : NSObject {
NSData *data;
uint index;
}
@property (nonatomic, assign) uint index;
@property (nonatomic, copy) NSData *data;
and then, when all your operations have returned you should have an array of MyData objects. Just sort them by index to get them in the initial order :) Then extracting the data should be simple.
I've assumed that you don't want to just one operation at a time :)
Do you really need all the results? I imagine that if you are developing an autosuggest component you should be interested in the last result only. If this is the case you could send the "-(void)cancelAllOperations" message to your NSOperationQueue before you add your last operation to be processed. This way the operations that are in waiting state will be canceled and the ones that are being processed have the opportunity to check their "cancel" state before they return data.
精彩评论