根据您的回答,您可以通过使用将块作为参数的块来做一些更通用(和棘手)的事情:
typedef void (^CallbackBlock)(NSError* error, NSObject* response);
- (void) performBlock:(void (^)(CallbackBlock callback)) blockToExecute retryingNumberOfTimes:(NSUInteger)ntimes onCompletion:(void (^)(NSError* error, NSObject* response)) onCompletion {
blockToExecute(^(NSError* error, NSObject* response){
if (error == nil) {
onCompletion(nil, response);
} else {
if (ntimes <= 0) {
if (onCompletion) {
onCompletion(error, nil);
}
} else {
[self performBlock:blockToExecute retryingNumberOfTimes:(ntimes - 1) onCompletion:onCompletion];
}
};
});
}
然后围绕您的异步 HTTP 请求,如下所示:
[self performBlock:^(CallbackBlock callback) {
[...]
AFHTTPRequestOperationManager *manager = [WSManager getHTTPRequestOperationManager];
[manager POST:base parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
dispatch_async(dispatch_get_main_queue(), ^(void){
if (callback) {
callback(nil, responseObject);
}
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (callback) {
NSError* errorCode = [[NSError alloc] initWithDomain:AppErrorDomain code:[operation.response statusCode] userInfo:@{ NSLocalizedDescriptionKey :error.localizedDescription}];
callback(errorCode, nil);
}
}];
} retryingNumberOfTimes:5 onCompletion:^(NSError *error, NSObject* response) {
//everything done
}];
这样,重试等待 HTTP 请求完成,您不必在每个请求方法中实现重试循环。