我想按顺序执行一系列 AFJSONRequestOperation ,并且能够在失败时中断队列。
目前,我这样做的方式并不可靠,因为有时下一个操作将有机会开始。
我有一个单例来调用我的 api 端点
AFJSONRequestOperation *lastOperation; // Used to add dependency
NSMutableArray *operations = [NSMutableArray array]; // Operations stack
AFAPIClient *httpClient = [AFAPIClient sharedClient];
[[httpClient operationQueue] setMaxConcurrentOperationCount:1]; // One by one
然后我以这种方式添加操作
NSMutableURLRequest *request = ...; // define request
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// Takes care of success
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
[[httpClient operationQueue] setSuspended:YES];
[[httpClient operationQueue] cancelAllOperations];
}];
[push:operation addDependency:lastOperation];
[operations $push:operation]; // This is using ConciseKit
lastOperation = operation;
// Repeat with other operations
// Enqueue a batch of operations
[httpClient enqueueBatchOfHTTPRequestOperations:operations ...
麻烦的是,有时跟随失败的操作仍然有机会开始。
因此,似乎只有 1 个并发操作最大值和一个依赖链不足以告诉队列等到故障回调完全执行之后。
这样做的正确方法是什么?
谢谢