2

据我所知,名为*WithContentsOfURL:的方法如[NSData dataWithContentsOfURL:]是同步的。Objective-C - 使用GCD和NSURLConnection的后台线程

所以,如果我想从3个网址下载使用异步方法*WithContentsOfURL:我已经把它们放在一个GCD调度,如:使用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?这将是(有点),相当于下面的方法在异步下载方面:

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内会发生什么?

回答

0

他们并不是真正的等同,因为使用NSURLConnectionDelegate可以让你喜欢的东西请求失败作出反应,身份验证挑战等。

您使用GCD给出的第一个示例适用于有效的URL,但对于其他任何情况都会导致不返回任何数据。像Eugene建议并使用ASIHTTPRequest一样 - 这很容易。

0

只需使用ASIHTTPRequest,异步请求实施有你就必须做这样的事情:

ASIHTTPRequest *myRequestOne = [ASIHTTPRequest requestWithURL:URLOne]; 

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

[myRequestOne startAsynchronous];