Objective-C - 使用GCD和NSURLConnection的背景线程

时间:2011-11-10 22:58:15

标签: objective-c asynchronous nsurlconnection grand-central-dispatch

据我所知,*WithContentsOfURL:这个名为[NSData dataWithContentsOfURL:]的方法是同步的。

因此,如果我想使用*WithContentsOfURL:方法异步下载3个URL,我必须将它们放在GCD调度中,如:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSData *dataOne = [NSData dataWithContentsOfURL:dataOne];
    NSData *dataTwo = [NSData dataWithContentsOfURL:dataTwo];
    NSData *dataThree = [NSData dataWithContentsOfURL:dataThree];

});

NSURLConnection在幕后使用GCD“吗?在异步下载方面,这是否(某种程度上)等同于以下方法:

NSURLRequest *myRequestOne = [NSURLRequest requestWithURL:[NSURL URLWithString:URLOne] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *myConnectionOne = [[NSURLConnection alloc] initWithRequest:myRequestOne delegate:self];

NSURLRequest *myRequestTwo = [NSURLRequest requestWithURL:[NSURL URLWithString:URLTwo] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *myConnectionThree = [[NSURLConnection alloc] initWithRequest:myRequestTwo delegate:self];

NSURLRequest *myRequestThree = [NSURLRequest requestWithURL:[NSURL URLWithString:URLThree] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *myConnectionThree = [[NSURLConnection alloc] initWithRequest:myRequestThree delegate:self];

如果我将NSURLConnection置于dispatch_async内,会发生什么?

2 个答案:

答案 0 :(得分:0)

只需使用ASIHTTPRequest,就可以在那里实现异步请求,您只需执行以下操作:

ASIHTTPRequest *myRequestOne = [ASIHTTPRequest requestWithURL:URLOne];

[myRequestOne setCompletionBlock:^ {
  // do something with [request responseData];
}];

[myRequestOne startAsynchronous];

答案 1 :(得分:0)

它们并不是真正等效的,因为使用NSURLConnectionDelegate可以对请求失败,身份验证挑战等内容做出反应。

您使用GCD提供的第一个示例适用于有效的URL,但对于任何其他内容,将导致不返回任何数据。像Eugene建议并使用ASIHTTPRequest一样 - 它更容易。