我想按顺序执行一系列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个并发操作和一个依赖链不足以告诉队列等待直到故障回调完全执行之后。
这样做的正确方法是什么?
谢谢
最佳答案
故障回调在主线程上执行,并且该操作(在后台线程上运行)不会等待它。因此,您需要进行一些编辑以防止在操作及其完成块完成之前启动下一个操作。
或者,不要将所有操作放在开始处的队列中,而是将操作列表保留在数组中,并在每次成功之后添加下一个操作。
关于ios - AFJSONRequestOperation-失败时中断操作队列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17131718/