我一直在使用NSURLConnection'ssendAsynchronousRequest:queue:completionHandler:方法,这很好.但是,我现在需要连续发出多个请求.

在仍然使用这种伟大的非同步方法的情况下,我如何做到这一点?

推荐答案

根据你想要的行为,有很多方法可以做到这一点.

您可以一次发送一组异步请求,跟踪已完成的请求数,并在所有请求完成后执行某些操作:

NSInteger outstandingRequests = [requestsArray count];
for (NSURLRequest *request in requestsArray) {
    [NSURLConnection sendAsynchronousRequest:request 
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        [self doSomethingWithData:data];
        outstandingRequests--;
        if (outstandingRequests == 0) {
            [self doSomethingElse];
        }
    }];
}

你可以把这些块连在一起:

NSMutableArray *dataArray = [NSMutableArray array];    
__block (^handler)(NSURLResponse *response, NSData *data, NSError *error);

NSInteger currentRequestIndex = 0;
handler = ^{
    [dataArray addObject:data];
    currentRequestIndex++;
    if (currentRequestIndex < [requestsArray count]) {
        [NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:currentRequestIndex] 
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:handler];
    } else {
        [self doSomethingElse];
    }
};
[NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:0] 
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:handler];

或者,您可以在一个非同步块中同步执行所有请求:

dispatch_queue_t callerQueue = dispatch_get_current_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL);
    dispatch_async(downloadQueue, ^{
        for (NSRURLRequest *request in requestsArray) {
            [dataArray addObject:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]];
        }
        dispatch_async(callerQueue, ^{
            [self doSomethingWithDataArray:dataArray];
        });
    });
});

另外,如果你使用其中任何一个,你应该添加一些错误判断.

Objective-c相关问答推荐

iOS - 如何预加载键盘?

如何使 UIView 动画序列重复和自动反转

Objective-C 和 Cocoa 有什么区别?

在 Objective-C 类中混合 C 函数

如何使用 Cocoa 创建临时文件?

iOS中CALayer的UIImage

来自 NSString 的 NSJSONSerialization

如何正确获取文件大小并将其转换为 Cocoa 中的 MB、GB?

何时使用静态字符串与 #define

NSUserDefaults 的限制是什么?

对块进行类型定义是如何工作的

在 Objective C 中使用 extern

iPhone 键盘、完成按钮和 resignFirstResponder

以流畅的动画显示/隐藏导航栏

NS_ASSUME_NONNULL_BEGIN 宏

点击手势识别器 - 哪个对象被点击了?

为什么 detailTextLabel 不可见?

如何从 UIColor 对象中获取红绿蓝 (RGB) 和 alpha?

UITableView ,重新加载时滚动到底部?

Xcode 在调试时判断表达式