问题
I have a basic question as to how the order of operations goes inside NSOperationQueue addOperationsWithBlock
.
What I want to do:
[_queue addOperationWithBlock:^{
//starts a new thread to download an image
//returns a response from the server
if (returnResponse != nil) {
//what I need to accomplish:
//1) Update the collectionViewCell with data
//2) Cache the image locally
//3) Save the image name in local database
}
}];
I don't need the code to do this, I just need to know how it works. For example, if I want to update the cell right away for the user, should I have that part of code right away like this?
if (returnResponse != nil) {
[[NSOperationQueue mainQueue]addOperationWithBlock^{
//update the cell content on the main Thread
}];
//write data to file, save image name in local database
}
My main question is: doing it this way, will caching the image and saving in local database be done on that separate thread, the one that was used to download the image? And if I reverse the order (cache the image, save in local database, then update the cell), will that make any difference?
SOLUTION:
After trying many different ways, I went with serial GCD inside NSOperationQueue mainQueue
. Trying to save in sqlite DB kept giving me a database is locked
error, even though I finalized and closed the databases correctly. I think because it was trying to save concurrently, leaving one database open at the same time another query was trying to access it. So the final solution for me looks like this:
[_queue addOperationWithBlock:^{
//starts a new thread to download an image
//returns a response from the server
if (returnResponse != nil) {
//Cache the image locally
[[NSOperationQueue mainQueue]addOperationWithBlock^{
//use a created GCD serial queue to save the image name in local database
//update the cell content on the main Thread
}];
}
}];
回答1:
Why don't you use GCD with concurrent queues? You could do something like the following:
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//execute first
dispatch_sync(concurrentQueue, blockOfCode);
//execute second
dispatch_sync(concurrentQueue, blockOfCode);
//execute third: update the UI
dispatch_sync(dispatch_get_main_queue(), blockOfCodeToUpdateUI);
回答2:
If you add the operation to the main queue ([NSOperationQueue mainQueue]
) then it will happen on the main queue.
As for the order of the steps, nobody can tell you that without more details. Presumably though, the view you are updating would be using the cached image or perhaps the one from the database? If that is the case, you probably want to update the models (cache, database) BEFORE you refresh the view.
来源:https://stackoverflow.com/questions/25471726/nsoperationqueue-addoperationwithblock-return-to-mainqueue-order-of-operations