NSOperationQueue addOperationWithBlock返回mainQueue的操作顺序

我有一个基本的问题,如何操作顺序进入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 } 

我的主要问题是:这样做,将caching图像和保存在本地数据库是在这个单独的线程,用于下载图像? 如果我颠倒了顺序(caching图像,保存在本地数据库,然后更新单元格),这将有所作为?

解:

尝试了很多不同的方法之后,我在NSOperationQueue mainQueue使用了串行GCD。 试图保存在sqlite数据库不断给我一个database is locked错误,即使我最后确定并closures数据库正确。 我想是因为它试图同时保存,在另一个查询试图访问它时同时打开一个数据库。 所以对我来说最终的解决scheme是这样的:

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

你为什么不用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); 

如果将操作添加到主队列( [NSOperationQueue mainQueue] ),则会在主队列上发生。

至于步骤的顺序,没有更多的细节,没有人可以告诉你。 据推测,你正在更新的视图将使用caching的图像或从数据库中的一个? 如果是这样的话,您可能需要在刷新视图之前更新模型(caching,数据库)。