Ios NSOperationQueue addOperationWithBlock返回主队列操作顺序

Ios NSOperationQueue addOperationWithBlock返回主队列操作顺序,ios,objective-c,nsoperationqueue,Ios,Objective C,Nsoperationqueue,我有一个基本问题,关于NSOperationQueue addOperationsWithBlock中的操作顺序 我想做的是: [_queue addOperationWithBlock:^{ //starts a new thread to download an image //returns a response from the server if (returnResponse != nil) { //what I need to accompl

我有一个基本问题,关于
NSOperationQueue addOperationsWithBlock
中的操作顺序

我想做的是:

[_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
    }
}];
我不需要代码来做这件事,我只需要知道它是如何工作的。例如,如果我想立即为用户更新单元格,我是否应该像这样立即获得该部分代码

if (returnResponse != nil) {
    [[NSOperationQueue mainQueue]addOperationWithBlock^{
        //update the cell content on the main Thread
    }];
    //write data to file, save image name in local database
}
我的主要问题是:这样做,缓存图像并保存在本地数据库中是否会在用于下载图像的单独线程上完成?如果我颠倒顺序(缓存图像,保存在本地数据库中,然后更新单元格),会有什么不同吗

解决方案:

在尝试了许多不同的方法之后,我在
NSOperationQueue mainQueue
中使用了串行GCD。尝试在sqlite DB中保存时,不断给我一个
数据库被锁定
错误,即使我正确地完成并关闭了数据库。我认为这是因为它试图并发保存,在另一个查询试图访问它的同时打开一个数据库。因此,我的最终解决方案如下所示:

[_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
        }];
    }
}];

如果将该操作添加到主队列(
[NSOperationQueue mainQueue]
),则该操作将在主队列上执行


至于步骤的顺序,没有更多细节,没有人能告诉你。不过,您正在更新的视图可能会使用缓存的图像,或者可能是数据库中的图像?如果是这种情况,您可能希望在刷新视图之前更新模型(缓存、数据库)。

为什么不将GCD用于并发队列? 您可以执行以下操作:

    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);