我已经为我当前正在开发的应用程序编写了一个同步类。
由于数据量很大,它首先获取数据计数,然后批量下载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
}];
}];
}];
这太混乱了,而且可能会变得非常混乱。
我还有其他方法可以处理这个问题吗?我唯一能想到的就是尝试让自己恢复活力。