【发布时间】:2012-03-13 15:09:44
【问题描述】:
我一直在使用 NSURLConnection's sendAsynchronousRequest:queue:completionHandler: 方法,这很棒。但是,我现在需要连续发出多个请求。
如何在仍然使用这种出色的异步方法的同时做到这一点?
【问题讨论】:
标签: objective-c ios ios5 nsurlconnection
我一直在使用 NSURLConnection's sendAsynchronousRequest:queue:completionHandler: 方法,这很棒。但是,我现在需要连续发出多个请求。
如何在仍然使用这种出色的异步方法的同时做到这一点?
【问题讨论】:
标签: objective-c ios ios5 nsurlconnection
根据你想要的行为,有很多方法可以做到这一点。
您可以一次发送一堆异步请求,跟踪已完成的请求数量,并在完成后执行一些操作:
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];
});
});
});
附:如果你使用其中任何一个,你应该添加一些错误检查。
【讨论】:
dispatch_async 这里正在使用后台线程。但是从后台请求调用同步请求并没有错。事实上,documentation 明确阻止您在 GUI 应用程序的主线程中发出同步请求,因为它会阻塞 UI。
sendAsynchronousRequest:queue:completionHandler: 异步发送请求(即在后台,不阻塞主线程)。当响应返回时,处理程序块被分派到指定队列中指定的队列。
completionHandlers 没有在并行线程中执行。它们被添加到mainQueue 并一次执行一个。当 HTTP 响应到达时,Cocoa 内部可能在幕后进行了某种多线程处理,以处理将块放到mainQueue 上,但它已被抽象出来,您无需担心。如果您以前在 JavaScript 中使用过 AJAX,那么您会熟悉这种顺序执行完成处理程序的行为。