我已经为我目前正在开发的应用程序编写了一个同步类。
由于数据量很大,它首先获取数据计数,然后将下载批量处理为NSOperationQueue. 这一切都很好,我已经让同步算法快速运行。
它的工作方式如下...
- (void)synchroniseWithCompletionHandler://block for completion handler
                            errorHandler://block for error handler
{
    [self.queue addOperationWithBlock
     ^{
           //Create an NSURLRequest for the first batch
           //Send the request synchronously
           //Process the result
           //If error then cancel all operations in the queue, run errorHandler and return.
      }];
    [self.queue addOperationWithBlock
     ^{
           //Create an NSURLRequest for the second batch
           //Send the request synchronously
           //Process the result
           //If error then cancel all operations in the queue, run errorHandler and return.
      }];
    //Add all the remaining batches.
    [self.queue addOperationWithBlock
     ^{
           completionHandler();
      }];
}
这样可以将内存使用量保持在最低水平,并将速度保持在最大水平。这个想法是下载和进程都在同一个块中,并且在继续队列中的下一个操作之前都已处理。
除了,我们现在已经在服务器上实现了 OAuth2 来对调用进行身份验证。
我通过 NXOAuth2 库设置 NXOAuth2Request 来完成这项工作。然后设置帐户并提取签名的 URL 请求。然后我像以前一样使用这个 NSURLRequest。
这样做的问题是,如果 OAuth 令牌在同步中途过期,则同步失败。
NXOAuth2 库有一个功能......
+ (void)performMethod:(NSString *)aMethod
           onResource:(NSURL *)aResource
      usingParameters:(NSDictionary *)someParameters
          withAccount:(NXOAuth2Account *)anAccount
  sendProgressHandler:(NXOAuth2ConnectionSendingProgressHandler)progressHandler
      responseHandler:(NXOAuth2ConnectionResponseHandler)responseHandler;
这通过在执行令牌刷新后重新发送请求来处理过期令牌的情况。
但是,这个函数是异步的,所以我不确定如何最好地将它放入我的同步程序中。
我可以使用它添加操作,然后将处理放入完成块中。但是这样做意味着所有下载几乎都将同时运行,然后无法保证下载处理的顺序(由于数据依赖性,我需要以严格的顺序处理它们。
我现在能想到的唯一方法是将它们菊花链在一起......
[NXOAuth2Request performFirstRequest...
    {
        deal with the data.
        [NXOauth2Request performSecondRequest...
            {
                deal with the data.
                [NXOauth2Request performThirdRequest...
                    {
                        deal with the data.
                        finish
                     }];
             }];
      }];
这只是混乱,可能会变得非常混乱。
有没有其他方法可以处理这个?我能想到的唯一另一件事就是尝试让自己焕然一新。