NSURLConnection的代理默认是在主线程运行的网络
-(void)viewDidLoad { NSString *strUrl = @""; strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strUrl]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; [con setDelegateQueue:[[NSOperationQueue alloc] init]]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@", [NSThread currentThread]); } 输出:{number = 1, name = main}
设置NSURLConnection的代理在子线程运行,须要执行 [con setDelegateQueue] 方法async
-(void)viewDidLoad { NSString *strUrl = @"; strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strUrl]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; [con setDelegateQueue:[[NSOperationQueue alloc] init]]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@", [NSThread currentThread]); } 输出:{number = 3, name = (null)}
注:调用[con setDelegateQueue]方法,参数不能传递主线程,否则会卡死线程;oop
-(void)viewDidLoad { dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSString *strUrl = @""; strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strUrl]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; }); } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@", [NSThread currentThread]); }
将网络请求放到子线程中执行,网络请求操做是不会执行的.这是由于NSURLConnection须要在RunLoop中执行,NSURLConnection 的start方法的注释中写到:若是在调用网络请求时没有指定RunLoop或operation queue,connection会被指定在当前线程的RunLoop的default模式中运行;url
-(void)viewDidLoad { dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSString *strUrl = @""; strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strUrl]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; }); //让当前线程的RunLoop运行起来 [[NSRunLoop currentRunLoop] run]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@", [NSThread currentThread]); }